Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Programming 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.
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
Vi Editor
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.
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
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
Expression in C
The purpose of printf function is to print values using the standard output
Comments in C
Standard Library in C
Control Structure in C
1. if :
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);
}
}
}
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;
}
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.
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
#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;
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);
}
// 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));
//relational
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++;
}
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.
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.
int f1 (int n)
{
int x;
x = f2 (n - 1, n - 2);
return x * 2;
}
int factorial(int x)
{
if(x==1)return 1;
else
return x*factorial(x-1);
}
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...