You are on page 1of 62

Lab Session 4

Programming in
Linux

Editing, compiling and running C programs in Linux

Introduction
C was developed at Bell Laboratories in 1972 by Dennis Ritchie.
Finally in 1972, a co-worker of Ken Thompson, Dennis Ritchie, returned
some of the generality found in BCPL to the B language in the process of
developing the language we now know as C.
C's power and flexibility soon became apparent. Because of this, the UNIX
operating system which was originally written in assembly language was almost
immediately re-written in C (only the assembly language code needed to
"bootstrap" the C code was kept). During the rest of the 1970's, C spread
throughout many colleges and universities because of its close ties to UNIX and
the availability of C compilers. Soon, many different organizations began using
their own versions of C causing compatibility problems. In response to this in
1983, the American National Standards Institute (ANSI) formed a committee to
establish a standard definition of C which became known as ANSI Standard C.
Today C is in widespread use with a rich standard library of functions.

Introduction
Significant Features of C
C is a powerful, flexible language that provides fast program execution and
imposes few constraints on the programmer.
It allows low level access to information and commands while still
retaining the portability and syntax of a high level language. These qualities
make it a useful language for both systems programming and general
purpose programs.
C's power and fast program execution come from it's ability to access low
level commands, similar to assembly language, but with high level syntax.
Its flexibility comes from the many ways the programmer has to accomplish
the same tasks.
C includes bitwise operators along with powerful pointer manipulation
capabilities.
C use of modularity. Sections of code can be stored in libraries for re-use
in future programs.
The core C language leaves out many features included in the core of other
languages.

C- Language Overview

The UNIX operating system, the C compiler, and essentially all UNIX applications programs
have been written in C.
The C has now become a widely used professional language for various reasons.
Easy to learn

Structured language
It produces efficient programs.
It can handle low-level activities.
It can be compiled on a variety of computer platforms.

Facts about C
C was invented to write an operating system called UNIX.
C is a successor of B language which was introduced around 1970s
The language was formalized in 1988 by the American National Standard Institute
(ANSI).
The UNIX OS was totally written in C by 1973.
Today C is the most widely used and popular System Programming Language.
Most of the state-of-the-art softwares have been implemented using C.
Today's most popular Linux OS and RBDMS MySQL have been written in C.

Why to use C???


C was initially used for system development work, in particular the
programs that make-up the operating system.
C was adopted as a system development language because it
produces code that runs nearly as fast as code written in assembly
language.
Some examples of the use of C might be:
Operating Systems
Language Compilers
Assemblers
Text Editors
Print Spoolers
Network Drivers
Modern Programs
Databases
Language Interpreters
Utilities

Why to use C???

Strength :
+ Efficiency: intended for applications where
assembly language
had traditionally been used.
+ Portability: hasnt splintered into incompatible
dialects; small
and easily written
+ Power: large collection of data types and
operators
+ Flexibility: not only for system but also for
embedded system
commercial data processing
+ Standard library
+ Integration with UNIX

Creating and Compiling C


Common editors to create C program by Shell are : Gedit /Text editor

GUI Text Editor like notepad or wordpad


Pico/Nano editor
simple text editor
Pico/nano editors are easier to use (most command options
are displayed at the bottom of the screen

Vi Editor

Open editor to create c files with


FileName dot
extension C (name.c)

Eg. gedit first.c , nano hello.c, vi name.c


and etc

Compile and Run C Program


How to Compile and Run a C Program on Ubuntu Linux
Steps :
Create C programs (Use a any editor) eg. gedit hello.c

// first progrma to display hello world


/*comment */
#include <stdio.h>
// Preprocessor (header file)
main()
// Preprocessor (header file)
{
printf("Hello World\n");
// program statement (body)
}
Compile the program , type the command gcc -o hello hello.c invoke
the
GNU C compiler to compile the file hello.c and output (-o) the result to an
executable called hello.
Execute the program , type the command ./hello This should result in the output
Hello World

You can execute the C program using command gcc


(Compile:syntax:gcc o executable objectname
$ gcc -o hello hello.c
source filename.c
Compile:e.g: gcc o one one.c
$ ./hello
Run:./one

Identifiers in C
Identifiers also called programmer defined words used to represent and
reference certain program entities.
Variable, function, and user-defined type names are all examples of
identifiers.
In C identifiers are sequences of letters, digits, and underscores from one to
several characters in length.

Rules for constructing Identifiers


1. Identifiers can consists of the capital letter A to Z, the lowercase letters a
to z, the digits 0 to 9, the underscore character.
2. The first character must be a letter or underscore.
3. There is virtually no length limitation. However, in many
implementations of the C language, the compiler recognizes only the
first 32 characters as significant.
4. There can be no embedded blanks.
5. Reserved words cannot be used as identifiers.
6. Identifiers are case sensitive. Therefore Tax and tax are valid identifiers
but distinct.

Keywords

Data Type
A data type is a set of data values and a set of operations on those
values. C has two classes of data types:
1. Built-in data types (that are recognized by the C
programming language)
2. Programmer-defined data types (that can be defined by the
programmer)
C also has two classes of built-in data types:
3. Fundamental data types: corresponds to the most common.
fundamental data type in C are in int , char and float.
float tax, int x, char f , double z, .
2. Derived data types: are derived form fundamental and
programmer-defined types using some operators.
eg. array, string and structures are derived data types

Data Type
Basic data type in C are: Integer:
1. Signed
Short integer(short, short int, signed short, signed short int)
Integer (int, signed, signed int)
Long integer( long, long int, signed long, signed long int)
2. Unsigned
Short integer ( unsigned short, unsigned short int)
Integer (unsigned, unsigned int)
Long integer (unsigned long, unsigned long int)
Floating-point:
1. Floating-point (float)
2. Double floating-point (double)
3. Long double floating-point (long double)
Character (char)

Constant
Constants: are identifiers whose value is fixed and does not change during the
execution of a program in which it appears.
In C the declaration of a named constant begins with the keyword const,
continues with a type specifier for the constant, and concludes with an
initialization for the identifier that will be treated as a named constant as shown
in the example below.
const int idnumber = 34;
The preprocessor #define is another more flexible method to define constants in
a program.
#define TRUE 1
#define FALSE 0
#define NAME_SIZE 20
Here TRUE, FALSE and NAME_SIZE are constant

thmetic Operators

Equality Operators

Operators in C

Operators in C

C operators and operator precedence

Operators in C

Relational Operators
Relational operators are used to compare values. An expression that compares
two expressions using a relational operator is called a simple predicate.
C has six relational operators:
Equal to = =
Less than or equal to <=
Not equal to !=
Greater than, >
Less than <
Greater than or equal to >=
These may be used in expressions of the form:
<value1> <relational operator> <value2>
p
Logical (Boolean) Operators
There are three operators that are commonly used to combine expressions
involving relational operators.
These are 3 logical operators:
and &&
or ||
not!

Operators in C
Increment and Decrement Operators
The operators ++ and - are called increment and decrement
operators.
a++ and ++a are equivalent to a += 1.
a-- and --a are equivalent to a -= 1.
++a op b is equivalent to a ++; a op b;
a++ op b is equivalent to a op b; a++;
p Example
Let b = 10 then
(++b)+b+b = 33
b+(++b)+b = 33
b+b+(++b) = 31
b+b*(++b) = 132

Casting Operator

Explicit Type Conversions: The Cast Operator and Casting


In C explicit type conversion is possible through the use of cast operator.
The operation of explicitly converting the type of an expression in temporary
storage to a specified type is called casting and its form is as follow:
(type) Expression
where Type is a type specifier such as int, double, or char.
Let us assume that we have the following declaration:
double first = 4.7;
int second = 27;
p
then we can use cast operator to convert the type of the operands in the
statements below:

Expression in C

Expression is a combination of operators,

variables based on the


rule of programming language rule .
Example of Expression in c :
1. a = b += c++ - d + --e / -f
2. a = b += (c++) - d + --e / -f
3. a = (b += (((c++) d) + ((--e) / (-f))))
p
4. (a = (b += (((c++) d) + ((--e) / (-f)))))
5. (A || B)
6. num1 > num2
7. a++
8. expr1? expr2:expr3; if expr1 is true then expr2 else
expr3 (conditional expressions with Ternary Operator)
9. Printf(%d=%d,a, (a+b)*c);

Input and Output Function

The Standard Output Function printf

The purpose of printf function is to print values using the standard output

device, the monitor screen.


There are two syntactical forms for the printf function call:
printf (FormatControlString); or
printf(FormatControlString, PrintList);
An example of the first form is the output statement
printf (This is Ethiopia); which prints the string constant
This is Ethiopia on the monitor screen.
For the second form let see the following declaration and output statement:
float distance = 550.0;
printf (The distance from Addis Ababa to Bahirdar is %f KM, distance);
it prints the string constant
The distance from Addis Ababa to Mekelle is 550 KM
on
the monitor screen.expr1, expr2, ..)
printf(string,

string: ordinary characters and conversion specification


%d --- int
%s --- string %f --- float

Input and Output Function


We can use the following format specifiers in the format control string of the
printf function:

The Standard Input Function scanf


As printf function the declaration of the standard library function scanf is
contained in the header file <stdio.h>.
The syntax of the scanf function call is as follows:
scanf (FormatControlString, InputList);
The following input and output statements accept the distance from Addis
Ababa to Bahirdar from the user of the program.
printf (What is the distance from Addis Ababa to Bahirdar);
scanf(%lf, &distance);
The ampersand character & tell the scanf function where to find the variable
into which values are to be stored. The format specifiers in the format control
string of the scanf function is similar to printf as shown above.

Comments in C

Comments are explanations or annotations that are included in a program


for documentation and clarification purposes.
Program comments describe the purpose of a program, function, or
statement and they are completely ignored by the compiler.
There are two ways to specify a comment in the C language.
a) /* and */ to surround comments, or
b) // (line comment) to begin comment lines.
Rules for program comments
1) The character /* start a comment. Such a comment can run any number
of lines and over line boundaries. A comment that starts with /* should be
terminated by the character */.
2) The character // start a line comment. Such a comment terminates at the
end of the line on which it occurs. If a line comment runs several lines,
each line must begin with //.
3) The comment characters //, /*, and */ are treated like other characters in
a // comment.

Standard Library in C

A. stdio library used for interactive I/O (input output) operations.


# include <stdio.h>
B.math library contains some standard mathematical functions such as square root
logarithm, trigonometry, etc.
C.string library which is needed for character string processing.
Each of such libraries consists of a header file & some object programs
corresponding to the routines (functions) declared in the file. Most header
files have the extension .h. To use a standard library you must put:
# include<StandardLibrary.h> at the start of your program.

Standard Library in C .. More header files

1.<complex.h> complex number arithmetic


2.<errno.h> Macro reporting error conditions
3.<float.h> limit float types
4.<inttypes.h > format conversation of integer type
5.<limits.h> sizes of basic types
6.<math.h> common mathematical functions
7.<stdarg.h> variavle arguments
8.<stdatomic.h> atomic types
9.<stdbool.h> Boolean type
10.<stdint.h> Fixed-width integer types
11.<stdio.h> input/output
12.<stdnoreturn.h> Non-returning functions
13.<string.h> String handling
14.<tgmath.h > typed-generic math (macros wrapping math.h and complex.h)
15.<threads.h> thread library
16.<time.h> Time/date utilities
17.<stdlib.h> general utilities: memory Managements , program utilities, String converstions ,
random numbers

Standard Library in C .. More header files


Dynamic memory management: Defined in header <stdlib.h>
a)malloc : allocates memory (function)
b)calloc: allocates and zeroes memory(function)
c)realloc: expands previously allocated memory block
d)free: deallocates previously allocated memory
e)aligned_alloc: allocates aligned memory

Program support utilities: Defined in header <stdlib.h>


f) abort : causes abnormal program termination (without cleaning up)
g) exit : causes normal program termination with cleaning up
h) quick_exit : causes normal program termination without completely cleaning up
i) atexit : registers a function to be called on exit() invocation (function)

Pseudo-random number generation : Defined in header <stdlib.h>


j) rand: generates a pseudo-random number (function)
k) srand : seeds pseudo-random number generator (function)
l) RAND_MAX: maximum possible value generated by rand(() (macro constant)
m)signal: sets a signal handler for particular signal (function)
n) raise: runs the signal handler for particular signal (function)
o) sig_atomic_t: the integer type that can be accessed as an atomic entity from an asynchronous signal handler
p) (typedef)
q) SIG_DELSIG_IGN: defines signal handling strategies (macro constant)
r) SIG_ERR: error was encountered (macro constant)

Control Structure in C

Control structure (instruction) enables us to specify the order in which


instructions in a program are to be executed by the computer, i.e. it determines the
flow of control in a program.
a)The sequence control structure:
step by step sequence
b)The decision (conditional) control structure
if and
switch
c)Loop control structure :
For
while and
do

1. if :

Control Structure in C / conditional

If statement: The syntax of an if-statement is


if (<expression>)
<statement>;
2. If-else statement: An if-statement may be followed immediately by an else-statement.
The syntax of an else-statement is
if (<expression>)
<statement>;
else
<statement>;
/* end if */
3. Nested If-Else statement: is formed when an entire if-else construct within either the body of
the if-statement or the body of the else statement. This is also called nesting of ifs.
The syntax of nested if statement is:
if (<expression>){
or
if (<expression>){
<statement>;
<statement>;
if (<expression>)
else
<statement>;
if (<expression>)
else
<statement>;
<statement>;
else
else
<statement>;
<statement>;
}

Control Structure in C / conditional


4. Switch case The switch statement provides a very useful alternative to
multiple if statements. It is used in conjunction with the case and default
statements. The syntax is
switch(integral expression) statement
The controlled statement, known as the switch body will consist of a
sequence of case statements.
The syntax of a case statement is
case constant-integral-expression : statement
The flow of control then continues from that point until a break is
encountered or the end of the switch body is encountered. A break statement
takes control out of the switch body.
If none of the case labels match the value of the switch expression then no
part of the code in the switch body is executed unless a default statement
appears within the switch body.

Example

The example program below is a variant of a program that we have already seen in
nested if-else statement.
#include<stdio.h>
main()
{
int n1,n2; char c;
char inbuf[30];
while(1)
{ printf("Enter Expression ");
if(gets(inbuf) == NULL) break;
scanf(inbuf,"%d%c%d",&n1,&c,&n2);
switch(c)
{
case '+' :
printf("%d\n",n1+n2);
break;
case '-' :
printf("%d\n",n1-n2);
break;
case '*' :
printf("%d\n",n1*n2);
break;
case '/' :
printf("%d\n",n1/n2);
break;
default :
printf("Unknown operator %c\n",c);
}
}
}

Control Structure in C / loops


1. For loop
The for statement provides an alternative way of programming loops. The
syntax of the for statement is as follow:
For ( InitializationExpression; LoopControlExpression; UpdateExpression )
LoopBody
/*end for*/
In this syntax InitializationExpression is a C expression that may assign an
initial value to a loop control variable, and UpdateExpression is one that may
change value. The LoopControlExpression is an expression that computes to
zero (for false) or a nonzero value (for true).
In executing a for statement, the computer does the following:
a)Executes the InitializationExpression.
b)Evaluate the LoopControlExpression. If it computes to zero, the loop is exited.
c)If the LoopControlExpression yields a nonzero value, the LoopBody is
executed and then the UpdateExpression is evaluated.
d)Test the LoopControlExpression again. Thus the LoopBody is repeated until
the LoopControlExpression computes to a zero value.

Control Structure in C / loops


1. Example
main()
{
int i;
for(i=0;i<10;i++)
printf("%d %d %d\n",i,i*i,i*i*i);
}

It will produce the output:


0 0 0
11 1
29 27
34 8
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729

Control Structure in C / loops


2. While Loop The while statement provides a means for repeated
execution of controlled statements. Usually uses in the case where
we may not know in advance how many times the loop should be
executed.
The basic form is:
while ( <expression> )
statement
and the meaning is that the expression is evaluated and if the value of
the expression is non-zero then the controlled statement is executed
otherwise the statement after the while statement is executed

Control Structure in C / loops


3. Do loop The while statement may be described as pretest (testbefore-execute). If the controlling expression is initially zero then the
controlled statement is never executed. There is an alternative
version that is sometimes useful. This is the do statement which may
be described as posttest (execute-before-test). This is sometimes
called a one-trip-loop referring to the fact that the loop "body" is
always executed at least once.
The syntax is: do
<statement>;
while (<expression>) ;
The controlled statement is always executed at least once.

Break and Continue


A break statement consists simply of the word break followed by a semicolon. Its effect is to cause immediate exit from the enclosing while
statement. It has the same effect when used with for and do statements.
A Continue :- controls the flow of loops to cause immediate back to Loop.
If you are executing a loop and hit a continue statement, the loop will stop its
current iteration, update itself (in the case of for loops) and begin to execute
again from the top
We can write the above example using break statement as follow:
main() {
int i = 0;
while(1) { /* OK to continue ? */
if(i>=10) break;
// what is the effect if it is continue?
printf("%d %d %d\n",i,i*i,i*i*i);
i++;
}
}

Break and Continue

Example:
main(){
Output:int max;
Enter largest number : 15
int sum=0,count=0;
There are 11 numbers not divisible by 4
int i=0;
and less than 15
printf("Enter largest number ");
Their total is 81
scanf("%d",&max);
while(1)
{
i++;
if(i == max) break;
if(i%4 == 0) continue;
count++;
sum += i;
}
printf("There are %d numbers not divisible by 4"
" and less than
%d\nTheir total is %d\n",
count,max,sum);
}

Nested Loops
A nested loop is a repetition structure that contains one or
more loops in its body. In a nested loop structure, in every
repetition of the outer loop the inner loops are completely
executed.
A loop contained in another loop forms a doubly nested loop.
A doubly nested loop can be placed inside another loop to
form triply nested loop, and so on.
In C a nested loop structure may be formed using while, for,
and do-while statements.

Nested Loops
The following example shows nested while loops being used to print out
multiplication tables.
The output will be as follows:
main()
{
1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
int i=1,j;
3 6 9 12 15 18 21 24 27 30 33 36
while(i <= 12) /* goes "down" page */
4 8 12 16 20 24 28 32 36 40 44 48
5 10 15 20 25 30 35 40 45 50 55 60
{
6 12 18 24 30 36 42 48 54 60 66 72
j = 1;
7 14 21 28 35 42 49 56 63 70 77 84
24 32 40 48 56 64 72 80 88 96
while(j <= 12) /* goes "across" page */ 89 16
18 27 36 45 54 63 72 81 90 99 108
{
10 20 30 40 50 60 70 80 90 100 110 120
11 22 33 44 55 66 77 88 99 110 121 132
printf(" %3d",i*j);
12 24 36 48 60 72 84 96 108 120 132 144
j++;
}
printf("\n"); /* end of line */
i++;
}
}

Function in C
Function is a self contained block of code that performs a specific task of the same kind.
The term function is synonymous with the term procedure.
Every C program can be thought as a collection of those functions.
Functions must be identified by programmer-defined names.
To avoid ambiguities, C requires that function names be unique in a source program file.
In all modular programs one of the modules is the main function.
The main function is identified by the word main.
Program execution always begins and eventually terminates in the main function.
Functions provide a convenient way of packaging up pieces of code so that they can be used
over and over again.
Sample program code 1
#include<stdio.h>
result = sum(var1,var2); //calling
int sum(int, int); //Prototype
printf("SUM = %d",result);
main(){
}
int var2,var1,result;
result = 0;
int sum(int a,int b) //definition
printf("Enter the first number\n");
{
scanf("%d" ,&var1);
int c=0;
printf("Enter the second number\n");
c = a + b;
scanf("%d", &var2);
return c;
}

Function in C .. Function Prototype

In general, all functions in a C program must be declared except the function main, which
must not be declared.
A function declaration, also called function prototype, consists of:
function type, function name, list of function parameter types enclosed parenthesis
terminal semicolon (;)
If the function has no formal parameters, the list of function parameter types is written as
(void) or ( ).
If the function has more than one formal parameter type, the list must be separated by
commas.
For the above sample code:
Function type is int i.e. the return type of the function is integer.
Function name is sum
List of function parameters types are (int, int).
Note: Before a function is called, it must be either defined or declared by a prototype in the
source file. The declaration of function defines a region in a program in which that function may
be used by other functions. This region is the scope of the function. The scope of the function
declared using a global prototype begins at the point where its prototype is placed and extends
until the end of the source file. The scope of a function declared by a local prototype, on the
other hand, begins at the point where its prototype is placed and extends until the end of the
function in which it appears. In general, in single source file programs, we will place function
prototypes right after the pre-processor directives and before the definition of function main.

Function in C.. Calling Function

Functions for which a definition exists in a program can be called by any function,
including the function main. However, the reverse is not true: programmer-defined
functions may not call the function main.
A function call requires the name of the function followed by a list of actual parameter
(arguments), if any, enclosed in parentheses ends with semicolon. For instance, in the above
sample program code to call the function sum we use the statement:
sum(var1,var2);
When a function call is encountered, the program control passes to the called function.
Next, the code corresponding to the called function is executed.
After the function body completes its execution, the program control goes back to the
calling function.

Reading Assignment
1.Actual and Formal Parameter
2.Return statement in Function and
3.Recursion

Function in C.. Calling By Reference


The call by reference method of passing arguments to a
function copies the address of an argument into the formal
parameter.
Inside the function, the address is used to access the actual
argument used in the call. This means that changes made to the
parameter affect the passed argument.
To pass the value by reference, argument pointers are passed to
the functions just like any other value.
So accordingly you need to declare the function parameters as
pointer types as in the following function swap(), which
exchanges the values of the two integer variables pointed to
by its arguments.

Function in C.. Calling By Reference

let us call the function swap() by passing values by reference


as in the following example:

#include <stdio.h>
/* function declaration */
void swap(int *x, int *y);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable
a and ,
* &b indicates pointer to b ie. address of variable
b. */
swap(&a, &b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;

/* function definition to swap the values */


void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
Output:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
Which shows that the change has reflected
outside of the function as well unlike call by
value where changes do

Function in C.. Calling By Value


The call by value method of passing arguments to a function
copies the actual value of an argument into the formal
parameter of the function.
In this case, changes made to the parameter inside the function
have no effect on the argument.
By default, C programming language uses call by value method to
pass arguments.
In general, this means that code within a function cannot alter the
arguments used to call the function.
Consider the function swap() definition as follows.

Function in C.. Calling By Value


Now, let us call the function swap() by passing actual values as in the
following example:
#include <stdio.h>
/* function declaration */
void swap(int x, int y);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values */
swap(a, b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}

/* function definition to swap the values */


void swap(int x, int y)
{
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
}
Output:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
Which shows that there is no change in the values
though they had been changed inside the function.

Part 1: First C Program


Exercise 1
Open text editor and type the following source code, Save as first.c and
compile it
//This is the first C program code
#include<stdio.h>
main()
{
printf("HELLO WORLD");
}
Exercise 2 . Write c programs which display the following output, save as
first1.c
THIS IS MY FIRST C PROGRAM CODE
I AM GOING TO BE A PROGRAMMER
I am C Compiler
Exercise 3 : Add your name and department at the top of your program code as
a comment in the format below
Name: **** ****
Department: Computer Science.

Part 2: Data types , declaration and type casting


//Second.c declare a variable
#include<stdio.h>
main()
{
int date;
float salary;
char Answer;
date = 5;
salary = 1050.50;
Answer = 'Y';
printf("Date = %d\n",date);
printf("salary = %f$\n",salary);
printf("Answer = %c",Answer);
}

Part 2: Data types , declaration and type casting


//Example

Second2.c
#include<stdio.h>
main()
{
int operand1;
float operand2;
int operand3;
float operand4;
int result1;
float result2;
operand1 = 10;
operand2 = 10.0;
operand3 = 3;
operand4 = 3.0;
// + addition operator
result1 = operand1 + operand3;
printf("Result1 = %d\n",result1);
result2 = operand2 + operand4;

printf("Result2 = %f\n",result2);
// - subtraction operator
result1 = operand1 - operand3;
printf("Result1 = %d\n",result1);
result2 = operand2 - operand4;
printf("Result2 = %f\n",result2);
//* multiplication
result1 = operand1 * operand3;
printf("Result1 = %d\n",result1);
result2 = operand2 * operand4;
printf("Result2 = %f\n",result2);
// / division
result1 = operand1 / operand3;
printf("Result1 = %d\n",result1);
result2 = operand2 / operand4;
printf("Result2 = %f\n",result2);
// % modulus (remainder)
result1 = operand1 % operand3;
printf("Result1 = %d\n",result1);
//result2 = operand2 % operand4;
//printf("Result2 = %f\n",result2);
}

Part 2: Data types , declaration and type casting


//Example

Second3.c Explicit type conversion (Casting)


// Syntax for type conversion = (Type) Expression
#include<stdio.h>
main(){
float first = 4.7;
int second = 27;
printf("Result = %d AND first = %f\n", (int)(first + second),first);
first = (int)first + second;
printf("Result = %f\n", first);
first = (int)first % second;
printf("Result = %f\n", first);
first = second % (int) first;
printf("Result = %f\n", first);
}

Part 3: Mathematical Library and Input output Function


// third.c
#include<stdio.h>
main()
{ char letter = 'A, int km=783, float mile=486.6376631;
//To print a variable of type char we use a format specifier %c
printf("The first letter in English Alphabet is: %c\n",letter);
//To print a variable of type int we use a format specifier %d
printf("\nThe distance from Addis Ababa to Mekelle is %d KM\n",km);
//To print a variable of type float we use a format specifier %f or %lf
printf("\nThe distance from Addis Ababa to Mekelle is %f Mile",mile);
}

// third1.c accepting values from the user using the standard input function
#include<stdio.h>
main()
{ int age,date;
printf("Enter your age\n");
//Standard input function scanf is used to accept input from users.
scanf("%d",&age);
printf("You are born in %d EC or in %d GC",(1999 - age),(2006 - age));

Part 3: Mathematical Library and Input output Function


// third2.c C Mathematical library
#include<stdio.h>
/ /The floating-point type function declarations are found in the math.h header file
#include<math.h>
//The integer type mathematical functions require the pre-processor directive #include
// <stdlib.h>
#include<stdlib.h>
main()
{
int y =-20,;
float x = 90.0;
//abs(y)returns the absolute value of y, where y is an integer.
printf("Absolute value of %d = %d\n",y,abs(y));
//cos(x)returns the cosine of x, where x is in radians.
printf("\nCosine of %f = %f\n",x,cos(x));
//sin(x)returns the sine of x, where x is in radians.
printf("\nSine of %f = %f\n",x,sin(x));
}

Part 3: Mathematical Library and Input output Function


Exercise 3: Write a C program that accepts the value of x, y & z from the user
and prints:
o the smallest integer larger than or equal to x
o the largest integer smaller than or equal to x
o the square root of y.
o z raised to the y power
Where the data type of x is float and y & z are int.

Part 4: Relational and logical Operators and Decisions Control Structure


//fourth.c Relational Operator
#include <stdio.h>main()
{
int x = 3;
int y = 4;
//relational operators
printf("Value of %d > %d is %d\n",x,y,x>y);
printf("Value of %d < %d is %d\n",x,y,x<y);
printf("Value of %d >= %d is %d\n",x,y,x>=y);
operators
printf("Value of %d <= %d is %d\n",x,y,x<=y);
printf("Value of %d == %d is %d\n",x,y,x==y);
}

//relational

Part 4: Relational and logical Operators and Decisions Control Structure


//fourth1.c Logical Operator
#include<stdio.h>
main()
{
int x=1,y=2,z=3;
int p,q;
p = (x>y) && (z<y); /* False i.e. 0 */
q = (y>x) || (y>z);
/* True i.e. 1 */
printf(" %d && %d = %d\n",p,q,p&&q);
printf(" %d || %d = %d\n",p,q,p||q); /* Can mix "logical" values and
arithmetic */
printf(" %d && %d = %d\n",x,q,x&&q);
printf(" %d || %d = %d\n",p,y,p||y);
/* Exercise the NOT operator */
printf(" ! %d = %d\n",p,!p);
printf(" ! %d = %d\n",q,!q);
/* NOT operator applied to arithmetic */
printf(" ! %d = %d\n",z,!z);
}

Part 4: Relational and logical Operators and Decisions Control Structure


//fourth2.c Decision Control structure (if)
#include<stdio.h>
main()
{
int p,q,r;
printf("Enter three numbers \n");
scanf("%d%d%d",&p,&q,&r);
if(( p<q && q<r ) || ( p>q && q>r))
printf("%d lies between %d and %d\n",q,p,r);
else
printf("%d does not lie between %d and %d\n",q,p,r);
}

Part 4: Relational and logical Operators and Decisions Control Structure


//fourth3.c Nested if else
Q(?)
#include<stdio.h>
Write a C program that accepts
main() {
float x;
an integer X from the user and
printf("Enter a number ");
determines that either the
scanf("%f",&x);
number is even or odd.
if(x > 0.0) {
printf("%f is positive\n",x);
printf("%f is the reciprocal\n",1.0/x);
}
else {
if (x == 0.0)
printf("Zero - no reciprocal\n");
else {
printf("%f is negative\n",x);
printf("%f is the reciprocal\n",1.0/x);
}
}
}

Part 4: Relational and logical Operators and Decisions Control Structure


//fourth4.c Switch case Structure
#include<stdio.h>
main()
{
int n1,n2;
char c;
while(1)
{
printf("Enter Expression ");
scanf("%d%c%d",&n1,&c,&n2);
if (n1 ==0 || n2==0)break;
switch(c)
{
case '+' :
printf("%d\n",n1+n2);
break;
case '-' :
printf("%d\n",n1-n2);
break;

case '*' :
printf("%d\n",n1*n2);
break;
case '/' :
printf("%d\n",n1/n2);
break;
default :
printf("Unknown operator %c\n",c);
}
}
}

//five1.c
Part 5: Loop Control Structure
//five.c For loop
#include<stdio.h>
main()
{
int i,j;
for(i=1;i<= 12;i++)
/* goes "down" page */
{
for(j=1;j<= 12;j++)
/* goes "across" page */
{
printf(" %3d",i*j);
}
printf("\n"); /* end of line */
}
}

while loop
#include<stdio.h>
main()
{
int i=1,j;
while(i <= 12) /* goes "down" page */
{
j = 1;
while(j <= 12) /* goes "across" page */
{
printf(" %3d",i*j);
j++;
}
printf("\n"); /* end of line */
i++;
}

Part 5: Loop Control Structure


//five2.c Do while loop
#include<stdio.h>
main()
{
int i=1,j;
/* goes "down" page */
do{
j = 1;
while(j <= 12)
/* goes "across" page */
{
printf(" %d",i*j);
j++;
}
printf("\n"); /* end of line */
i++;
}while(i <= 12);
}

Q(?)
Write a C program that accepts an
integer N from the user and calculate
the sum of all even numbers up to N
using for, while and do while loop.

Part 5: Loop Control Structure


The difference between while and do-while loop
//five4.c (while loop)
//five3.c (do-while loop)
#include<stdio.h>
#include<stdio.h>
main()
main()
{
{
int i = 0;
int i = 0;
while(i <10)
do
/* OK to continue ? */
{
{
printf("%d %d %d\n",i,i*i,i*i*i);
printf("%d %d %d\n",i,i*i,i*i*i);
i++;
i++;
} while(i < 10);
}
/* OK to continue ? */}
}

Q(?)

Write a program that asks the user to enter an integer between 1 and 10, sums
the squares of the integers from 1 to the number entered, and displays the sum.
For Example:, if the user enters 5, the program should display the following.
The sum of squares of integers from 1 to 5 is 55.

Part 6: Function Definition , Calling and Recursion


// six.c simple program to illustrate function calling
//This program returns ((x-1)(x-2)/2)*2
#include <stdio.h>
int f1 (int);
int f2 (int, int);
main ()
{
int x;
printf("Enter n:\n");
scanf("%d",&x);
printf("Result = %d",f1(x));
}

int f1 (int n)
{
int x;
x = f2 (n - 1, n - 2);
return x * 2;
}

// six1.c recursion function


#include<stdio.h>
int factorial(int);
main(){
int n;
printf("Enter an integer");
scanf("%d",&n);
printf("Factorial of %d= =%d",n,factorial(n));
}

int f2 (int a, int b)


{
int x;
x = a * b / 2;
return x;
}

int factorial(int x)
{
if(x==1)return 1;
else
return x*factorial(x-1);
}

Part 6: Function Definition , Calling and Recursion


// six2.c Parameter passing by reference
// simple program to illustrate parameter passing by reference [returns ((x-1)(x-2)/2)*2]
#include <stdio.h>
int f1 (int* n)
int f2 (int* a, int* b)
int f1 (int*);
{
{
int f2 (int*, int*);
int x,y,z;
main ()
int x;
y=*n-1;
{
z=*n-2;
x = (*a * *b) / 2;
int x;
x = f2 (&y,&z);
return x;
printf("Enter n:\n");
return x * 2;
}
scanf("%d",&x);
}
printf("Result = %d",f1(&x));
}

Q(?)
In a mathematical text a function f(x,y) is defined thus
f(x,y) = x - y if x<0 or y<0
f(x,y) = f(x-1,y) + f(x,y-1)
otherwise
Write a function to evaluate this equation for user supplied values of
x and y. Incorporate your function in a program that prompts the user
for the value of x and y and display the result of the function.

To Be Continued...

You might also like