Professional Documents
Culture Documents
1. Memory Hierarchy
Memory is categorized into volatile and nonvolatile memories, with the former requiring
constant power ON of the system to maintain data storage.
Furthermore, a typical computer system provides a hierarchy of different times of memories
for data storage.
2. Data movement
In order to perform computation, data must travel from the secondary storage to the CPU.
Due to the vast differences in access speed and storage capacity, the operating system
performs a series of sophisticated steps (both at the levels of hardware and the software).
Disk cache
The hard drive has a local data cache. Because the hard drive access speed is so much slower,
disk access are normally done asynchronously at the hardware level. The hard drive will be
instructed to fetch or save data from a physical location of a certain size. The hard drive
controller will acknowledge the instruction right away, and will take sometime to populate the
disk cache with the requested data block, and then, at a later time, raise an interrupt to notify
the interested party that the data access is complete. This model of interrupt based data transfer
is asynchronous.
The data transfer speed (from memory to hard drive or vice versa) depends on:
1. Registers
CPU registers are at the top most level of this hierarchy, they hold the most
frequently used data. They are very limited in number and are the fastest.
They are often used by the CPU and the ALU for performing arithmetic and
logical operations, for temporary storage of data.
2. Cache
The very next level consists of small, fast cache memories near the CPU.
They act as
staging areas for a subset of the data and instructions stored in the relatively
slow main memory.
There are often two or more levels of cache as well. The cache at the top
most level after the registers is the primary cache. Others are secondary
caches.
Many a times there is cache present on board with the CPU along with other
levels that are outside the chip.
3. Main Memory:
The next level is the main memory, it stages data stored on large, slow disks
often called hard disks. These hard disks are also called secondary memory,
which are the last level in the hierarchy. The main memory is also called
primary memory.
The secondary memory often serves as staging areas for data stored on the
disks or tapes of other machines connected by networks.
If the data your program needs are stored in a CPU register, then they can be
accessed in zero cycles during the execution of the instruction. If stored in a
cache, 1 to 30 cycles. If stored in main memory, 50 to 200 cycles. And if
stored in disk tens of millions of cycles. This is obviously delay being
introduced.
On the other hand, the cost per bit is the least for the secondary memory,
which is more at the primary memory level. This increases till at the register
level where it is the maximum.
Similarly, memory sizes are smallest at the register level. This increases to a
few KBs in the cache, few hundreds of MBs or even GBs nowadays in the
main memory, to hundreds of GB’s in the secondary memory.
Thus there is a tradeoff between cost, access time, size and all this needs to
be taken into account when designing the memory hierarchy for a computer
system.
Answer:
Assembler: Assembler is a software or a tool that translates Assembly language into machine code.
Assembler:
1. Assembler is a computer program that reads code written in one language which is called
Assembly language and translates into machine language.
2. Assembler is used in low-level Assembly language.
3. Assembler is less popular than compiler.
Compiler:
1. Compiler is a computer program that reads code (like C,C++ code )and translates into machine
language.
2. Compiler is used in high-level language.
3. Compiler is more popular than Assembler.
Comparison Chart
BASIS FOR
COMPILER ASSEMBLER
COMPARISON
Phases/ Passes The compilation phases are lexical Assembler makes two passes
Output The assembly code generated by the The relocatable machine code
Definition of Compiler
The compiler is a computer program that reads the program written in a
source language, translates it into equivalent assembly language and
forwards the assembly language code to the Assembler. While the
translation of the source code to assembly code the compiler also reports
the error in the source code to its user.
Definition of Assembler
Some compilers perform the task of assembler and directly generate a
relocatable machine code instead of assembly code, which is further directly
passed to linker /loader. The assembler takes as input the assembly code
generated by the compiler and translates it into relocatable machine code.
Even the simplest form of assembler performs two passes over the input.
The first pass detects all the identifiers in the assembly code that denotes
storage location and store them in the symbol table (other than compilers
symbol table). The storage location is assigned to the identifier that is
encountered in the first pass.
In the second pass, the input is scanned again, and this time
the operation code are translated into a sequence of bits representing
that operation in the machine code. The second pass also
translates identifiers into the addresses defined in the symbol table. Thus
the second pass generates the relocatable machine code.
COMPILER
The compiler works on a basic principle. It simply reads the whole program written on it. Then it
converts the whole program to the machine/computer language. For this process, the compiler
takes a lot of time to read the whole program or to analyze the whole program. The compilers are
generally the memory eaters. They need a lot of memory to complete their process. Because they
create the object code by analyzing the program written on them. They work fast as compared to
the interpreters. Because they have the very less execution time. In this process, the whole
program doesn’t require to be created/compiled every time. Languages like to C and the C++
commonly used the compilers.
ASSEMBLER
Assembler is also a compiler. But in the assembler, the source code is written in the Assembly
language. This assembly language is a simple language. And this language is understandable by
the humans as well. The work of an assembler is to convert the assembly language to the machine
language. The assembler works on the principle of the one to one mapping translation. There are
improvements coming in the assemblers day by day. They are becoming very easy and user-
friendly programs to use as well. The latest editions of the assemblers work very efficiently and
they help us in the debugging of the written code as well.
member definition;
member definition;
...
member definition;
};
union
A union is a special data type available in C that allows storing different data types in the same memory
location. You can define a union with many members, but only one member can contain a value at any
given time. Unions provide an efficient way of using the same memory location for multiple purposes.
Defining a Union: To define a union, you must use the union statement in the same way as you
did while defining a structure. The union statement defines a new data type with more than one member
for your program. The format of the union statement is as follows:
union [union name]
member definition;
member definition;
...
member definition;
};
// declaring structure
struct struct_example
{
int integer;
float decimal;
char name[20];
};
// declaraing union
union union_example
{
int integer;
float decimal;
char name[20];
};
void main()
{
// creating variable for structure
// and initializing values difference
// six
struct struct_example s={18,38,"geeksforgeeks"};
// difference five
printf("\n Accessing all members at a time:");
s.integer = 183;
s.decimal = 90;
strcpy(s.name, "geeksforgeeks");
u.integer = 183;
u.decimal = 90;
strcpy(u.name, "geeksforgeeks");
printf("\nstructure data:");
s.integer = 240;
printf("\ninteger: %d", s.integer);
s.decimal = 120;
printf("\ndecimal: %f", s.decimal);
u.decimal = 120;
printf("\ndecimal: %f", u.decimal);
//difference four
printf("\nAltering a member value:\n");
s.integer = 1218;
printf("structure data:\n integer: %d\n "
" decimal: %.2f\n name: %s\n",
s.integer, s.decimal, s.name);
u.integer = 1218;
printf("union data:\n integer: %d\n"
" decimal: %.2f\n name: %s\n",
u.integer, u.decimal, u.name);
}
Run on IDE
Output:
structure data:
integer: 18
decimal: 38.00
name: geeksforgeeks
union data:
integeer: 18
decimal: 0.00
name: ?
sizeof structure: 28
sizeof union: 20
decimal: 90.00
name: geeksforgeeks
union data:
integeer: 1801807207
decimal: 277322871721159510000000000.00
name: geeksforgeeks
structure data:
integer: 240
decimal: 120.000000
name: C programming
union data:
integer: 240
decimal: 120.000000
name: C programming
structure data:
integer: 1218
decimal: 120.00
name: C programming
union data:
integer: 1218
decimal: 0.00
name: ?
Documentation files or program source code files are usually stored as ASCII text. In
contrast, binary files, such as executable programs, graphical images, or word
processing documents, contain other characters that cannot be normally displayed
or printed, and are usually illegible to human beings.
The format of a file, whether ASCII or binary, becomes important when you are
transferring files between computers. For example, when using FTP, you can
transfer ASCII text files without any special consideration. To exchange binary files,
however, you may need to enter the command set binary or otherwise prepare the
client to transfer binary files, so that the computer will correctly transmit the special
characters in the file.
Note: Most current FTP software will automatically transfer ASCII and binary files
correctly.
Binary Addition
It is a key for binary subtraction, multiplication, division. There are four
rules of binary addition.
Binary Subtraction
Subtraction and Borrow, these two words will be used very frequently
for the binary subtraction. There are four rules of binary subtraction.
Example − Subtraction
Binary Multiplication
Binary multiplication is similar to decimal multiplication. It is simpler than
decimal multiplication because only 0s and 1s are involved. There are four
rules of binary multiplication.
Example − Multiplication
Binary Division
Binary division is similar to decimal division. It is called as the long division
procedure.
Example − Division
int main()
{
char arr[100];
strrev(arr);
return 0;
}
#include <stdio.h>
int main()
{
char s[1000], r[1000];
int begin, end, count = 0;
printf("Input a string\n");
gets(s);
end = count - 1;
r[begin] = '\0';
printf("%s\n", r);
return 0;
}
int main()
{
char a[100];
gets(a);
reverse(a, 0, strlen(a)-1);
printf("%s\n", a);
return 0;
}
c = *(x+begin);
*(x+begin) = *(x+end);
*(x+end) = c;
#include<stdio.h>
int string_length(char*);
void reverse(char*);
main()
{
char s[100];
printf("Enter a string\n");
gets(s);
reverse(s);
return 0;
}
length = string_length(s);
begin = s;
end = s;
begin++;
end--;
}
}
return c;
}
Windows is a range of graphical interface operating systems that are developed and sold by
Microsoft. Early versions of Microsoft Windows ran on top of a separate version of DOS and
it ceased to be used when Windows 95 was launched as a stand-along operating system that
did not require a separate DOS license. With Windows 95 and 98, but not ME, the MS-DOS
component could be run without starting Windows. When DOS was no longer required to run
the system, it was completely stopped being used in PCs. The DOS is now obsolete and is
very rarely used in the real world. DOS and Windows differ from each other greatly even
though Windows is believed to be derived from DOS.
DOS also offered less storage space compared to Windows. The highest storage space that
DOS offered came around 2 gigabyte, while the latest Windows offers storage space in
terabytes. Windows can also accommodate much larger hard drives, while DOS cannot due
to its dependence on FAT16 file system.
DOS and Windows also differ in terms of registry systems and swap files. While DOS uses a
directory system, where all the files are contained within a particular directory or a
subdirectory, Windows uses a much complicated registry system making it difficult to
manually delete files from the system and excessive files can cause the system to slow down
or crash.
DOS Windows
Text is used as the basic input Uses a mouse for all operating
Input System
system commands. system input.
Windows is a multitasking
DOS is unable to run multiple operating system; allowing more
Multitasking
processes at the same time. than one process to work
simultaneously.
Due to the decline of usage for DOS, most versions of DOS are now available for free in the
market. It is also simple to use and does not require gigabytes of memory in order to work
compared to Windows. DOS has become ideal for prototyping, testing, and making
automated systems that only require checking if and when something goes wrong. Due to its
simplicity in usage and lack of fancy GUIs, the system is also much cheaper to operate.
What is the difference between a DOS laptop and
Windows 8 laptop?
Well in a DOS laptop you get the default OS as FreeDOS. If you are interested to
know more then just google it up. In a windows laptop the original windows OS
comes preinstalled along with some softwares like antivirus,office and so on. Buying
a DOS laptop can save you a lot of bucks,probably around 2k to 3k but you will have
to go about installing windows OS and all the required drivers for your laptop. You
will not get any preinstalled softwares aslike a windows laptop. I bought a DOS laptop
6 months ago intending to save some money and I have never regretted my decision.
In fact I installed windows 8 after removing FreeDOS and it works like a charm. I
installed all the required drivers and softwares and I am very much satisfied. I also
got to learn some new things down the line and I am really very proud of the decision
that I took that day. So in short I would say 'No Pain No Gain'. So go for a DOS laptop
and also if you are not aware there are better options than windows like linux out
there which are completely free and powerful unlike windows. So just try to get some
hands on experience because it is better not to be spoonfed all the time.
matrices
Write a C program to read elements in two matrices and multiply them. Matrix
multiplication program in C. How to multiply matrices in C. Logic to multiply two
matrices in C programming.
Example
Input
Output
Product of matrices =
30 24 18
84 69 54
138 114 90
Matrix Multiplication
Two matrices can be multiplied only and only if number of columns in the first matrix
is same as number of rows in second matrix. Multiplication of two matrices is defined
as -
#include <stdio.h>
int main()
{
int A[SIZE][SIZE]; // Matrix 1
int B[SIZE][SIZE]; // Matrix 2
int C[SIZE][SIZE]; // Resultant matrix
/*
* Multiply both matrices A*B
*/
for(row=0; row<SIZE; row++)
{
for(col=0; col<SIZE; col++)
{
sum = 0;
/*
* Multiply row of first matrix to column of second matrix
* and store sum of product of elements in sum.
*/
for(i=0; i<SIZE; i++)
{
sum += A[row][i] * B[i][col];
}
C[row][col] = sum;
}
}
return 0;
}
Output
Enter elements in matrix A of size 3x3:
Enter elements in matrix A of size 3x3:
1 2 3
4 5 6
7 8 9
Product of matrix A * B =
30 24 18
84 69 54
138 114 90
9. Difference Between Recursion and
Iteration
May 30, 2016 Leave a Comment
Comparison Chart
BASIS FOR
RECURSION ITERATION
COMPARISON
variable.
Condition If the function does not converge to If the control condition in the
Infinite Repetition Infinite recursion can crash the Infinite loop uses CPU cycles
system. repeatedly.
Stack The stack is used to store the set of Does not uses stack.
Size of Code Recursion reduces the size of the Iteration makes the code longer.
code.
Definition of Recursion
C++ allows a function to call itself within its code. That means the definition
of the function possesses a function call to itself. Sometimes it is also called
“circular definition“. The set of local variables and parameters used by the
function are newly created each time the function calls itself and are stored
at the top of the stack. But, each time when a function calls itself, it does not
create a new copy of that function. The recursive function does not
significantly reduce the size of the code and does not even improve the
memory utilization, but it does some when compared to the iteration.
Let us understand recursion with a function which will return the factorial of
the number.
1. int factorial(int num){
2. int answer;
3. if (num==1) {
4. return 1;
5. }else{
6. answer = factorial(num-1) * num; //recursive calling
7. }
8. return (answer);
9. }
In above code, the statement in else part shows the recursion, as the
statement calls the function factorial( ) in which it resides.
Definition of Iteration
Iteration is a process of executing the set of instructions repeatedly till the
condition in iteration statement becomes false. The iteration statement
includes the initialization, comparison, execution of the statements inside the
iteration statement and finally the updating of the control variable. After the
control variable is updated it is compared again, and the process repeats
itself, till the condition in iteration statement turns out to be false. The
iteration statements are “for” loop, “while” loop, “do-while” loop.
The iteration statement does not use a stack to store the variables. Hence,
the execution of the iteration statement is faster as compared to recursive
function. Even the iteration function do not have the overhead of repeated
function calling which also make its execution faster than recursive function.
The iteration is terminated when the control condition becomes false. The
absence of control condition in iteration statement may result in an infinite
loop, or it may cause a compilation error.
In above code, the function returns the factorial of the number using
iteration statement.
Recursion vs Iteration
On another hand, iteration means repetition of the process until the condition fails.
For example – when you use loop (for, while etc.) in your programs.
ii) The iterative approach involves four steps, initialization, condition, execution and
updation.
iv) Recursion is slower than iteration due to the overhead of maintaining stack
whereas iteration is faster.
v) Recursion takes more memory than iteration due to the overhead of maintaining
the stack .
vi) If recursion is not terminated (or base condition is not specified) then it creates
stack overflow (where your system runs out of memory).
vii) Any recursive problem can be solved iteratively. But you can’t solve all problems
using recursion.
Both recursion and iteration are used for executing some instructions repeatedly
until some condition is true. A same problem can be solved with recursion as well as
iteration but still there are several differences in their working and performance that
I have mentioned below.
Recursion Iteration
a function calls itself again and again some statements are executed again
until some base condition is not and again using loops until some
used to store the current function Memory usage is less as it doesn’t use
Lets write the implementation of finding factorial of number using recursion as well
as iteration.
Recursion Example
1 #include <stdio.h>
4 if(n == 0)
5 return 1;
6 else
7 return n * factorial(n-1);
8 }
9
10 int main() {
12
13 return 0;
14 }
Iteration Example
1 #include <stdio.h>
3 int main() {
4 int i, n = 5, fac = 1;
7 fac = fac * i;
10
11 return 0;
12 }
void name()
or
void name()
{
void game() {
For a successful recursion, one must keep in mind that every call made in the recursion
process must simplify the computation. Recursion is achieved by defining a base case.
if (N == 0) return 1;
In this example, recursion can easily be seen in the statement (N*factorial(N-1)), where it is
calling the factorial function again. Recursion is very helpful as it helps in shortening of the
code. However, the recursion is a little slow in performance.
function factorial(n)
result = 1;
for(loop=1;loop<=n;loop++)
{
result = result * loop;
return result;
In this example, looping is achieved by using integers from 1 to n, and loop<=n statement is
used as a criteria to stop further looping. Thus, we can conclude that the same results can be
achieved by using a recursion and iteration. However, they both are based on approaches that
are a little different. Any recursive algorithm can also be written using iterations (loops).
Comparison between Recursion and Iteration:
Recursion Iteration
Iteration is achieved by an
Recursion refers to a iterative function which
recursive function in loops to repeat some
Definition
which it calls itself again section of the code.
to repeat the code.
Infinite recursion is
Infinite looping consumes
Infinite repetition capable of crashing the
CPU cycles repeatedly
system
----------------------------------------------------------------
Do While- your condition is at the end of the loop block, and makes obligatory to
enter the loop at least one time.
In D0-While, the code is first executed and then the condition is checked. The next
iteration is executed if the test result is true.
------------------------------------------------------------------
1. //while
2. while(condition is true)
3. {
4. something
5. }
6.
7.
8. //do-while
9. do
10. {
11. something
12. }while(condition is true)
13.
EXAMPLE :-
[code]
do
{
scan inputs
print "do you want to continue[y/n]?"
scan choice
}while(ch == 'y')
[/code]
This is not possible in While because it is an entry controlled loop.
But you can execute the same code in While in the following way.
1234567
1. ch = 'y'
2. while(ch == 'y')
3. {
4. do something
5. print "do you want to continue[y/n]?"
6. scan choice
7. }
Just copy paste the below source code to arrange numbers in descending order in C
compiler to test, how the source code works. Happy Learning.
#include <stdio.h>
void main ()
{
//variable declaration
int number[30];
int i, j, a, n;
a = number[i];
number[i] = number[j];
number[j] = a;
23
16
23
16
C Program to Display
12.
Fibonacci Sequence
Example on how to display the Fibonacci sequence of first n numbers (entered by the
user) using loop. Also in different example, you learn to generate the Fibonacci
sequence up to a certain number.
The Fibonacci sequence is a series where the next term is the sum of pervious two
terms. The first two terms of the Fibonacci sequence is 0 followed by 1.
Output
nextTerm = t1 + t2;
while(nextTerm <= n)
{
printf("%d, ",nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return 0;
}
Output
You can divide up your code into separate functions. How you divide up
your code among different functions is up to you, but logically the division
is such that each function performs a specific task.
Defining a Function
The general form of a function definition in C programming language is as
follows −
Return Type − A function may return a value. The return_type is the data
type of the value the function returns. Some functions perform the desired
operations without returning a value. In this case, the return_type is the
keyword void.
Function Name − This is the actual name of the function. The function name
and the parameter list together constitute the function signature.
Example
Given below is the source code for a function called max(). This function
takes two parameters num1 and num2 and returns the maximum value
between the two −
int result;
result = num1;
else
result = num2;
return result;
Function Declarations
A function declaration tells the compiler about a function name and how
to call the function. The actual body of the function can be defined
separately.
For the above defined function max(), the function declaration is as follows
−
int max(int num1, int num2);
Parameter names are not important in function declaration only their type
is required, so the following is also a valid declaration −
int max(int, int);
Calling a Function
While creating a C function, you give a definition of what the function has
to do. To use a function, you will have to call that function to perform the
defined task.
To call a function, you simply need to pass the required parameters along
with the function name, and if the function returns a value, then you can
store the returned value. For example −
Live Demo
#include <stdio.h>
/* function declaration */
int main () {
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
return 0;
int result;
result = num1;
else
result = num2;
return result;
We have kept max() along with main() and compiled the source code.
While running the final executable, it would produce the following result −
Max value is : 200
Function Arguments
If a function is to use arguments, it must declare variables that accept the
values of the arguments. These variables are called the formal
parameters of the function.
Formal parameters behave like other local variables inside the function and
are created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be
passed to a function −
1 Call by value
This method 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.
2 Call by reference
This method 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 argument.
CONTENTS
1. Overview and Key Difference
2. What is Function Prototype in C
3. What is Function Definition in C
4. Similarities Between Function Prototype and Function Definition in C
5. Side by Side Comparison – Function Prototype vs Function Definition in C in Tabular
Form
6. Summary
Function Prototype provides the function declaration. It specifies the name of the function,
the return types, the parameters. The return types are the data type that returns from the
function. When a function is returning an integer, then the return type is int. When a
function is returning a float value, then the return type is a float. If the function is not
returning any value, it is a void function. The function name is used to identify it. C
keywords cannot be used as function names. The data is passed to the function using
parameters. The function prototype does not contain the real implementation of the
function. The function prototype has the following syntax.
If there is a function to calculate the maximum of two numbers the declaration can be
written as int max (int num1, int num2); The maximum value should be found in num1 and
num2. Those are integers, and they are passed to the function. The return type, in the
beginning, is also int. So, the function returns an integer value. It t is not necessary to write
the parameter names in the function prototype. But it is necessary to write the data types.
Therefore, int max (int, int); is also a valid function prototype. If there are two integers as
num1, num2, num3 and the prototype is written as int max(int num1, int num2, num3); it
is invalid. The num1, num2 have the data types, but num3 does not have a data type.
Therefore, it is invalid.
#include <stdio.h>
int main(){
int p =10;
int q= 20;
int answer;
answer = calMax(p,q);
return 0;
int value;
if(p>q) {
value = p;
else {
value = q;
return value;
According to the above, the second statement shows the function prototype. It does not
have the implementation. The actual implementation is after the main program. The
function prototypes are more useful when defining a function in one source file and call
that function in another in another file.
The function definition has the actual implementation of the function. It contains what the
function should do. When the program calls the function, the control is transferred to the
called function. After the execution of the function, the control returns back to the main
function. The required data is passed to the function as a parameter list. If there is a value
returning, then the return type is mentioned. If there are no returning values, the return
type is void. Refer the below function to calculate the area of a triangle.
#include <stdio.h>
float calArea(int x, int y);
int main () {
int p =10;
int q= 20;
flaot area;
area = calArea(p,q);
return 0;
float value;
value = 0.5 * x * y;
return value;
According to the above program, the second statement indicates the function prototype.
The actual implementation of what the function performs is written after the main program.
It is the function definition. The p and q values are passed to the calArea function. The
variable value is a local variable to the calArea function. The area is calculated and
assigned to the variable value. Then it is returned back to the main program.
What are the Similarities Between Function Prototype and Function Definition
in C?
Implementation
The function prototype does not have the function The function definition has the function
implementation. implementation.
Using functions in programs has advantages. Functions increase code reusability. It is not
necessary to write the same code again and again. Instead, the programmer can divide
the program and call the necessary function. In C there are library functions. These
functions are declared in the C header files. Some of them are printf (), scanf () etc. The
programmer can also write their own functions. There are two terms which are associated
with functions in C. They function prototype and function definition. The difference
between the function prototype and function definition in C is that the function prototype
only contains the declaration of the function while the function definition contains the actual
implementation of the function.
int main()
{
int x, y, temp;
printf("Enter the value of x and y\n");
scanf("%d%d", &x, &y);
temp = x;
x = y;
y = temp;
return 0;
}
Output of program:
#include <stdio.h>
void swap(int*, int*); //Swap function
declaration
int main()
{
int x, y;
swap(&x, &y);
return 0;
}
//Swap function definition
void swap(int *a, int *b)
{
int t;
t = *b;
*b = *a;
*a = t;
}
#include <stdio.h>
int main()
{
int a, b;
a = a + b;
b = a - b;
a = a - b;
To understand the logic choose the variables 'a' and 'b' as '7' and '9'
respectively and then do what is being done by the program. You can
choose any other combination of numbers as well. Sometimes it's an
excellent way to understand a program.
Swap two numbers using pointers
#include <stdio.h>
int main()
{
int x, y, *a, *b, temp;
a = &x;
b = &y;
temp = *b;
*b = *a;
*a = temp;
return 0;
}
int main()
{
int x, y;
x = x ^ y;
y = x ^ y;
x = x ^ y;
return 0;
}
1. #include <stdio.h>
2.
3. void swap(int*, int*);
4.
5. int main()
6. {
7. int x, y;
8.
9. printf("Enter the value of x and y\n");
10. scanf("%d%d",&x,&y);
11.
12. printf("Before Swapping\nx = %d\ny = %d\n", x, y);
13.
14. swap(&x, &y);
15.
16. printf("After Swapping\nx = %d\ny = %d\n", x, y);
17.
18. return 0;
19. }
20.
21. void swap(int *a, int *b)
22. {
23. int temp;
24.
25. temp = *b;
26. *b = *a;
27. *a = temp;
28. }
29.
2. C
3. Swapping numbers using Call by Value
Output:
Before Swapping
Output:
x = 10
y=5
Values of a and b is 5 10
After Swapping
x = 10
y=5
Example :
1. #include<stdio.h>
2. #define size 5
3. int main()
4. {
5. int i;
6. for(i=0;i<size;i++)
7. printf(“Hello”);
8. }
Above program will print “Hello” five time.
But compiler won’t understand where printf actually defined and what is size.
So we need some one to process the code and replace header files and macros before
sending it to compiler which is named preprocessor .
“ A software program which process the c file and replace some of the things (header
file , macros etc) before sending the code to compiler called Preprocessor ”
Preprocessor
A software program that processes the source file before sending it to
actual compilation is called preprocessor.
Pictorial Explanation
While Processing the source file, the preprocessor replaces header files
and macros with defined files and values.
The line which starts with '#' will be processed before the actual
compilation starts.
Preprocessor Tasks
Macro expansion
#define size 5. Here size is a macro which holds the value 5. Before the
compilation starts, the preprocessor will replace size by 5 all over the
program.
Conditional compilation
With the help of preprocessor, we can decide which part of the source
code should compile and which part of the code should be ignored while
compilation. We will discuss conditional compilation in upcoming topics.
Source File - Before Preprocessing
Example
#include<stdio.h>
#define size 5
int main()
{
int i = 0;
return 0;
}
After Preprocessing
Example
int main()
{
int i = 0;
return 0;
}
This preprocessed code will be sent to the compiler for further actions.
The C preprocessor modifies a source file before handing it over to the compiler, allowing
conditional compilation with #ifdef, defining constants with#define, including header files
with #include, and using builtin macros such as __FILE__. Here is lists of the preprocessor
directives, or commands to the preprocessor, that are available:
#include
#define
#undef
#if
#ifdef
#ifndef
#error
__FILE__
__LINE__
__DATE__
__TIME__
__TIMESTAMP__
pragma
# macro operator
## macro operator
C Programming Functions
C Programming User-defined functions
C Programming Recursion
You will learn to find the factorial of a number using recursion in this example. Visit
this page to learn, how you can find the factorial of a number using loop.
Output
Factorial of 6 = 720
Initially, the multiplyNumbers() is called from the main() function with 6 passed as an
argument.
Numbers larger than 9, having two or more digits in the decimal system,
are expressed digit by digit. For example, the BCD rendition of the base-10
number 1895 is
11101100111
Other bit patterns are sometimes used in BCD format to represent special
characters relevant to a particular system, such as sign (positive or
negative), error condition, or overflow condition.
WhatIs.com
Follow:
A UPS contains a battery that "kicks in" when the device senses a loss of
power from the primary source. If you are using the computer when the
UPS notifies you of the power loss, you have time to save any data you are
working on and exit gracefully before the secondary power source (the
battery) runs out. When all power runs out, any data in your computer's
random access memory (RAM) is erased. When power surges occur, a
UPS intercepts the surge so that it doesn't damage the computer.
Voltage and frequency independent (VFI) UPS systems are called dual
or double conversion because incoming AC is rectified to DC to keep
batteries charged and drive the inverter. The inverter re-creates steady AC
power to run the IT equipment.
Figure 1.
When power fails the batteries drive the inverter, which continues to run the
information technology (IT) load. When power is restored, either from the
utility or a generator, the rectifier delivers direct current (DC) to the inverter
and simultaneously recharges the batteries. The inverter runs full time.
Utility input is completely isolated from the output, and bypass is only used
for maintenance safety or if there's an internal electronics failure. Since
there is no break in the power delivered to the IT equipment, vacuum fault
interrupter (VFI) is generally considered the most robust form of UPS. Most
systems synchronize the output frequency with the input, but that's not
necessary, so it still qualifies as frequency independent.
Figure 2.
Every power conversion incurs a loss, so the wasted energy has historically
been considered the price of ultimate reliability. The newest VFI systems
claim better than 96% efficiency at nearly all loads.
When incoming power fails, or the voltage goes out of range, the bypass
quickly disconnects from the input and the battery drives the inverter. When
input power is restored, the bypass re-engages the input, re-charges the
batteries, and keeps output voltage constant. UPS vendors who use
paralleled power sources claim no loss of reliability. The result is around
98% energy efficiency.
Figure 4.
New VFD concepts have the inverter producing power within 2 ms after
being activated. The bypass is normally engaged, just as with VI, so
equipment operates directly from the utility or generator. Since the inverter
isn't working until power fails, there is no voltage control or power
consumed, enabling efficiencies as high as 99%. Power failure or voltage
outside of range opens the bypass switch, disengaging input from output;
the inverter starts operating from the batteries. The rectifier is only large
enough to keep the batteries charged.
UPS - Uninterruptible Power Supply
By Steven McFadyen on August 21st, 2013
UPS are used to safeguard various types of equipment. One of the common uses is computers,
particularly in data centres and the critical equipment of large organizations.
Contents [hide]
Note: the above UPS description is that of a static (electronic) UPS. While this is the most common type of
UPS, there are other technologies, for example, rotary UPS and the use of flywheels to store the energy.
In addition to protecting equipment in the event of mains failure, because the first convert the a.c. to
d.c, a UPS has the added benefit of being able to solve other problems related to power supply
quality. These include voltage dips, harmonics, frequency variations, etc. For more information, you
can see the note 9 power supply issues solved by using a UPS.
Another element to batteries is the discharge time. Any battery backed UPS will only be rated for a
certain period (5 minutes, 15 minutes, 30 minutes, etc.). For this reason, most UPS applications are
centred around providing sufficient power for a limited time to enable any necessary actions - safely
shut down the equipment, change over to generator power, etc.
To ensure functioning, operational safety and Electromagnetic Compatibility (EMC) requirements are
achieved, UPS are manufactured to recognized standards, the most important of which is:
UPS Configurations
The arrangement of rectifier, inverter, battery and other components can be carried out in different
ways. Each arrangement has advantages and disadvantages. Normally the more robust the
configuration, the more expensive the UPS.
In a standby UPS, power is normally supplied directly from the mains and the inverter only switched in
if the mains fails. This can have the advantages of cheaper cost and higher efficiencies. On-line UPS
always supply the load via the inverter. These are more expensive, but because the inverter is
always used they can resolve many power quality issues.
Standby UPS
In a standby UPS, the static (electronic) transfer switch supplies the load directly with mains
power. In the event of power failure, the static transfer switch immediately changes over to power
from the inverter.
Static transfer switches when switching from mains to inverter power, will typically do this in less than
5 mS. The battery is always kept at full charge by the rectifier and immediately available for supplying
power. Often a filter provides some power conditioning when supply mains power to the load. A
surge arrestor protects the UPS and loads from over voltage conditions.
A big advantage of on-line UPS is that the load is always supplied by the inverter and many power
quality issues on the mains are eliminated. For more information, you can see the 9 power supply issues
solved by using a UPS note.
Ferro-resonant [standby] - the load is supplied by a three winding transformer, with the mains on one input
winding and the inverter on the other. The transformer provides some level of Ferro-resonant power
conditioning and voltage regulation. During a mains failure, the switching from mains to inverter power is by a
static transfer switch.
Line Interactive [on-line] - in this configuration, the load is always supplied by the inverter. There is no
rectifier and the batteries are charged by running the inverter in reverse when the main power is normal. A
transfer switch changes the input of the inverter from main to battery on mains failure.
Delta Conversion [on-line] - is a relatively new and patented technology. This technology use converters cable
of both rectification and inverting, together with a delta transformer to supply the load. Some of the mains
power is directly used to supplement the load inverter output to create a better inverter efficiency.
Configuration Comparison
Standby On-Line
Typical Power 0.0-0.5 kVA 3-15 kVA 5-5000 kVA 0.5-5.0 kVA 5-5000 kVA
UNIX Introduction
What is UNIX?
UNIX systems also have a graphical user interface (GUI) similar to Microsoft Windows
which provides an easy to use environment. However, knowledge of UNIX is required for
operations which aren't covered by a graphical program, or for when there is no windows
interface available, for example, in a telnet session.
Types of UNIX
There are many different versions of UNIX, although they share common
similarities. The most popular varieties of UNIX are Sun Solaris, GNU/Linux,
and MacOS X.
Here in the School, we use Solaris on our servers and workstations, and
Fedora Linux on the servers and desktop PCs.
The UNIX operating system is made up of three parts; the kernel, the shell and the
programs.
The kernel
The kernel of UNIX is the hub of the operating system: it allocates time and memory to
programs and handles the filestore and communications in response to system calls.
As an illustration of the way that the shell and the kernel work together, suppose a user
types rm myfile (which has the effect of removing the file myfile). The shell searches
the filestore for the file containing the program rm, and then requests the kernel,
through system calls, to execute the program rm on myfile. When the process rm
myfile has finished running, the shell then returns the UNIX prompt % to the user,
indicating that it is waiting for further commands.
The shell
The shell acts as an interface between the user and the kernel. When a user logs in, the
login program checks the username and password, and then starts another program
called the shell. The shell is a command line interpreter (CLI). It interprets the
commands the user types in and arranges for them to be carried out. The commands are
themselves programs: when they terminate, the shell gives the user another prompt (%
on our systems).
The adept user can customise his/her own shell, and users can use different shells on
the same machine. Staff and students in the school have the tcsh shell by default.
The tcsh shell has certain features to help the user inputting commands.
History - The shell keeps a list of the commands you have typed in. If you need to
repeat a command, use the cursor keys to scroll up and down the list or type history for
a list of previous commands.
Examples of files:
All the files are grouped together in the directory structure. The file-system is arranged
in a hierarchical structure, like an inverted tree. The top of the hierarchy is traditionally
called root (written as a slash / )
In the diagram above, we see that the home directory of the undergraduate
student "ee51vn" contains two sub-directories (docs and pics) and a file
called report.doc.
An UNIX Terminal window will then appear with a % prompt, waiting for you to start
entering commands.
UNIX
By Vangie Beal
Related Terms
C
operating system - OS
UUCP - Unix-to-Unix Copy
z/OS
OS/400
cloud OS
Linux OS (Operating System)
Chromium OS
Firefox OS
OS/2
(Pronounced yoo-niks) UNIX is a popular multi-user, multitaskingoperating system (OS) developed at Bell Labs in
the early 1970s. Created by just a handful of programmers, UNIX was designed to be a small, flexible system
Due to its portability, flexibility, and power, UNIX has become a leading operating system for workstations.
UNIX History
UNIX was one of the first operating systems to be written in a high-level programming language, namely C. This
meant that it could be installed on virtually any computer for which a C compiler existed. This natural portability
combined with its low price made it a popular choice among universities. It was inexpensive because antitrust
Bell Labs distributed the operating system in its source language form, so anyone who obtained a copy could
modify and customize it for his own purposes. By the end of the 1970s, dozens of different versions of UNIX were
running at various sites. After its breakup in 1982, AT&T began to market UNIX in earnest. It also began the long
operating system that is certified by The Open Group to use the UNIX trademark conforms to the Single UNIX
Specification. The latest version of the certification standard is UNIX V7, aligned with the Single UNIX
According to The Open Group's Web site, "As the owner of the UNIX trademark, The Open Group has separated
the UNIX trademark from any actual code stream itself, thus allowing multiple implementations. Since the
introduction of the Single UNIX Specification, there has been a single, open, consensus specification that defines
the requirements for a conformant UNIX system. There is also a mark, or brand, that is used to identify those
products that have been certified as conforming to the Single UNIX Specification, initially UNIX 93, followed
subsequently by UNIX 95, UNIX 98 and now UNIX 03. Both the specification and the UNIX trade mark are
managed and held in trust for the industry by The Open Group."
Note: Not all commands are part of UNIX itself and may not work on all UNIX machines. This page lists more
Previous Page
Next Page
What is Unix ?
The Unix operating system is a set of programs that act as a link between
the computer and the user.
The computer programs that allocate the system resources and coordinate
all the details of the computer's internals is called the operating
system or the kernel.
There are various Unix variants available in the market. Solaris Unix, AIX, HP
Unix and BSD are a few examples. Linux is also a flavor of Unix which is freely
available.
Several people can use a Unix computer at the same time; hence Unix is called
a multiuser system.
A user can also run multiple programs at the same time; hence Unix is a
multitasking environment.
Unix Architecture
Here is a basic block diagram of a Unix system −
The main concept that unites all the versions of Unix is the following four
basics −
Kernel − The kernel is the heart of the operating system. It interacts with the
hardware and most of the tasks like memory management, task scheduling
and file management.
Shell − The shell is the utility that processes your requests. When you type in
a command at your terminal, the shell interprets the command and calls the
program that you want. The shell uses standard syntax for all commands. C
Shell, Bourne Shell and Korn Shell are the most famous shells which are
available with most of the Unix variants.
Commands and Utilities − There are various commands and utilities which
you can make use of in your day to day activities. cp, mv, cat and grep, etc.
are few examples of commands and utilities. There are over 250 standard
commands plus numerous others provided through 3rd party software. All the
commands come along with various options.
Files and Directories − All the data of Unix is organized into files. All files
are then organized into directories. These directories are further organized
into a tree-like structure called the filesystem.
System Bootup
If you have a computer which has the Unix operating system installed in
it, then you simply need to turn on the system to make it live.
Login Unix
When you first connect to a Unix system, you usually see a prompt such
as the following −
login:
To log in
Have your userid (user identification) and password ready. Contact your
system administrator if you don't have these yet.
Type your userid at the login prompt, then press ENTER. Your userid is case-
sensitive, so be sure you type it exactly as your system administrator has
instructed.
Type your password at the password prompt, then press ENTER. Your
password is also case-sensitive.
If you provide the correct userid and password, then you will be allowed to
enter into the system. Read the information and messages that comes up on
the screen, which is as follows.
login : amrood
amrood's password:
Last login: Sun Jun 14 09:32:32 2009 from 62.61.164.73
$
Change Password
All Unix systems require passwords to help ensure that your files and data
remain your own and that the system itself is secure from hackers and
crackers. Following are the steps to change your password −
Step 2 − Enter your old password, the one you're currently using.
Step 3 − Type in your new password. Always keep your password complex
enough so that nobody can guess it. But make sure, you remember it.
Note − We have added asterisk (*) here just to show the location where
you need to enter the current and new passwords otherwise at your
system. It does not show you any character when you type.
You can use the ls command to list out all the files or directories available
in a directory. Following is the example of using ls command with -
l option.
$ ls -l
total 19621
drwxrwxr-x 2 amrood amrood 4096 Dec 25 09:59 uml
-rw-rw-r-- 1 amrood amrood 5341 Dec 25 08:38 uml.jpg
drwxr-xr-x 2 amrood amrood 4096 Feb 15 2006 univ
drwxr-xr-x 2 root root 4096 Dec 9 2007 urlspedia
-rw-r--r-- 1 root root 276480 Dec 9 2007 urlspedia.tar
drwxr-xr-x 8 root root 4096 Nov 25 2007 usr
-rwxr-xr-x 1 root root 3192 Nov 25 2007 webthumb.php
-rw-rw-r-- 1 amrood amrood 20480 Nov 25 2007 webthumb.tar
-rw-rw-r-- 1 amrood amrood 5654 Aug 9 2007 yourfile.mid
-rw-rw-r-- 1 amrood amrood 166255 Aug 9 2007 yourfile.swf
Here entries starting with d..... represent directories. For example, uml,
univ and urlspedia are directories and rest of the entries are files.
Who Are You?
While you're logged into the system, you might be willing to know : Who
am I?
Try it on your system. This command lists the account name associated
with the current login. You can try who am i command as well to get
information about yourself.
There are three commands available to get you this information, based on
how much you wish to know about the other users: users, who, and w.
$ users
amrood bablu qadir
$ who
amrood ttyp0 Oct 8 14:10 (limbo)
bablu ttyp2 Oct 4 09:08 (calliope)
qadir ttyp4 Oct 8 12:09 (dent)
Try the w command on your system to check the output. This lists down
information associated with the users logged in the system.
Logging Out
When you finish your session, you need to log out of the system. This is
to ensure that nobody else accesses your files.
To log out
Just type the logout command at the command prompt, and the system will
clean up everything and break the connection.
System Shutdown
The most consistent way to shut down a Unix system properly via the
command line is to use one of the following commands −
Sr.No. Command & Description
1 halt
2 init 0
Powers off the system using predefined scripts to synchronize and clean
up the system prior to shutting down
3 init 6
4 poweroff
5 reboot
6 shutdown
You typically need to be the super user or root (the most privileged account
on a Unix system) to shut down the system. However, on some standalone
or personally-owned Unix boxes, an administrative user and sometimes
regular users can do so.
The UNIX brand has traditionally been applied to the family of multitasking, multiuser computer
operating systems that derive from the original AT&T UNIX operating system, developed in the
1970s at the Bell Labs research center by Ken Thompson, Dennis Ritchie, and others --
[Source:Wikipedia link]
Today, The Open Group holds the definition of what a UNIX system is and its associated trademark
in trust for the industry. The latest version can be read online [link].
In 1994 Novell (who had acquired the UNIX systems business of AT&T/USL) decided to get out of
that business. Rather than sell the business as a single entity, Novell transferred the rights to the
UNIX trademark and the specification (that subsequently became the Single UNIX Specification) to
The Open Group (at the time X/Open Company). Subsequently, it sold the source code and the
product implementation (UNIXWARE) to SCO. The Open Group also owns the trademark
UNIXWARE.
Today, the definition of UNIX ® takes the form of the worldwide Single UNIX Specification
integrating X/Open Company's XPG4, IEEE's POSIX Standards and ISO C. Through continual
evolution, the Single UNIX Specification is the defacto and dejure standard definition for the UNIX
system application programming interfaces. As the owner of the UNIX trademark, The Open Group
has separated the UNIX trademark from any actual code stream itself, thus allowing multiple
implementations. Since the introduction of the Single UNIX Specification, there has been a single,
open, consensus specification that defines the requirements for a conformant UNIX system.
There is also a mark, or brand, that is used to identify those products that have been certified as
conforming to the Single UNIX Specification, initially UNIX 93, followed subsequently by UNIX 95,
UNIX 98, UNIX 03 and now UNIX V7.
The Open Group is committed to working with the community to further the development of
standards conformant systems by evolving and maintaining the Single UNIX Specification and
participation in other related standards efforts. Recent examples of this are making the
standard freely available on the web, permitting reuse of the standard in open source
documentation projects , providing test tools ,developing the POSIX and LSB certification
programs.
From this page you can read about the history of the UNIX system over the past 40 years or more.
You can learn about the Single UNIX Specification, and read or download online versions of the
specification. You can also get involved in the ongoing development and maintenance of the Single
UNIX Specification, by joining the Austin Group whose approach to specification development is
"write once, adopt everywhere", The Open Group's Base Working Group or get involved in
the UNIX Certification program.
break Statement
The break statement terminates the loop (for, while and do...while loop) immediately
when it is encountered. The break statement is used with decision making statement
such as if...else.
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
printf("Sum = %.2lf",sum);
return 0;
}
Output
Enter a n4: -3
Sum = 10.30
This program calculates the sum of maximum of 10 numbers. It's because, when the
user enters negative number, the break statement is executed and loop is
terminated.
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
printf("Sum = %.2lf",sum);
return 0;
}
Output
Enter a n10: 12
Sum = 59.70
In the program, when the user enters positive number, the sum is calculated
using sum += number; statement.
When the user enters negative number, the continue statement is executed and
skips the negative number from calculation.
Advertisements
Previous Page
Next Page
The last chapter explained the standard input and output devices handled
by C programming language. This chapter cover how C programmers can
create, open, close text or binary files for their data storage.
Opening Files
You can use the fopen( ) function to create a new file or to open an
existing file. This call will initialize an object of the type FILE, which
contains all the information necessary to control the stream. The prototype
of this function call is as follows −
FILE *fopen( const char * filename, const char * mode );
Here, filename is a string literal, which you will use to name your file, and
access mode can have one of the following values −
1 r
2 w
Opens a text file for writing. If it does not exist, then a new file is created.
Here your program will start writing content from the beginning of the file.
3 a
Opens a text file for writing in appending mode. If it does not exist, then
a new file is created. Here your program will start appending content in
the existing file content.
4 r+
5 w+
Opens a text file for both reading and writing. It first truncates the file to
zero length if it exists, otherwise creates a file if it does not exist.
6 a+
Opens a text file for both reading and writing. It creates the file if it does
not exist. The reading will start from the beginning but writing can only
be appended.
If you are going to handle binary files, then you will use following access
modes instead of the above mentioned ones −
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"
Closing a File
To close a file, use the fclose( ) function. The prototype of this function is
−
int fclose( FILE *fp );
Writing a File
Following is the simplest function to write individual characters to a stream
−
int fputc( int c, FILE *fp );
The function fputc() writes the character value of the argument c to the
output stream referenced by fp. It returns the written character written on
success otherwise EOF if there is an error. You can use the following
functions to write a null-terminated string to a stream −
int fputs( const char *s, FILE *fp );
The function fputs() writes the string s to the output stream referenced
by fp. It returns a non-negative value on success, otherwise EOF is
returned in case of any error. You can use int fprintf(FILE *fp,const
char *format, ...) function as well to write a string into a file. Try the
following example.
Make sure you have /tmp directory available. If it is not, then before
proceeding, you must create this directory on your machine.
#include <stdio.h>
main() {
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fclose(fp);
Reading a File
Given below is the simplest function to read a single character from a file
−
int fgetc( FILE * fp );
The fgetc() function reads a character from the input file referenced by
fp. The return value is the character read, or in case of any error, it
returns EOF. The following function allows to read a string from a stream
−
char *fgets( char *buf, int n, FILE *fp );
The functions fgets() reads up to n-1 characters from the input stream
referenced by fp. It copies the read string into the buffer buf, appending
a null character to terminate the string.
If this function encounters a newline character '\n' or the end of the file
EOF before they have read the maximum number of characters, then it
returns only the characters read up to that point including the new line
character. You can also use int fscanf(FILE *fp, const char *format,
...) function to read strings from a file, but it stops reading after
encountering the first space character.
#include <stdio.h>
main() {
FILE *fp;
char buff[255];
fp = fopen("/tmp/test.txt", "r");
fclose(fp);
When the above code is compiled and executed, it reads the file created
in the previous section and produces the following result −
1 : This
2: is testing for fprintf...
Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
1. Text files
Text files are the normal .txt files that you can easily create using Notepad or any
simple text editors.
When you open those files, you'll see all the contents within the file as plain text. You
can easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide least security
and takes bigger storage space.
2. Binary files
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a better
security than text files.
File Operations
In C, you can perform four major operations on the file, either text or binary:
FILE *fptr;
For Example:
fopen("E:\\cprogram\\newprogram.txt","w");
fopen("E:\\cprogram\\oldprogram.bin","rb");
Let's suppose the file newprogram.txt doesn't exist in the location E:\cprogram. The
first function creates a new file named newprogram.txt and opens it for writing as
per the mode 'w'.
The writing mode allows you to create and edit (overwrite) the contents of the file.
Now let's suppose the second binary file oldprogram.bin exists in the
location E:\cprogram. The second function opens the existing file for reading in
binary mode 'rb'.
The reading mode only allows you to read the file, you cannot write into the file.
File
Meaning of Mode During Inexistence of file
Mode
r Open for reading. If the file does not exist, fopen() returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.
File
Meaning of Mode During Inexistence of file
Mode
r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
Open for both reading and writing If the file exists, its contents are overwritten. If
wb+
in binary mode. the file does not exist, it will be created.
Closing a File
The file (both text and binary) should be closed after reading/writing.
They are just the file versions of printf() and scanf(). The only difference is that,
fprint and fscanf expects a pointer to the structure FILE.
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
This program takes a number from user and stores in the file program.txt.
After you compile and run this program, you can see a text file program.txt created in
C drive of your computer. When you open the file, you can see the integer you
entered.
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
fscanf(fptr,"%d", &num);
return 0;
}
This program reads the integer present in the program.txt file and prints it onto the
screen.
If you succesfully created the file from Example 1, running this program will get you
the integer you entered.
Other functions like fgetchar(), fputc() etc. can be used in similar way.
Reading and writing to a binary file
Functions fread() and fwrite() are used for reading from and writing to a file on the
disk respectively in case of binary files.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
return 0;
}
We declare a structure threeNum with three numbers - n1, n2 and n3, and define it in
the main function as num.
Now, inside the for loop, we store the value into the file using fwrite.
The first parameter takes the address of num and the second parameter takes the
size of the structure threeNum.
Since, we're only inserting one instance of num, the third parameter is 1. And, the last
parameter *fptr points to the file we're storing the data.
fread(address_data,size_data,numbers_data,pointer_to_file);
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
return 0;
}
In this program, you read the same file program.bin and loop through the records
one by one.
In simple terms, you read one threeNum record of threeNum size from the file pointed
by *fptr into the structure num.
This will waste a lot of memory and operation time. An easier way to get to the
required data can be achieved using fseek().
As the name suggests, fseek() seeks the cursor to the given record in the file.
Syntax of fseek()
fseek(FILE * stream, long int offset, int whence)
The first parameter stream is the pointer to the file. The second parameter is the
position of the record to be found, and the third parameter specifies the location
where the offset starts.
Whence Meaning
SEKK_CUR Starts the offset from the current location of the cursor in the file.
Example of fseek()
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
return 0;
}
This program will start reading the records from the file program.bin in the reverse
order (last to first) and prints it.
& Binary AND Operator copies a bit to the result if it exists (A & B) =
in both operands. 12, i.e.,
0000 1100
<< Binary Left Shift Operator. The left operands value is A << 2 =
moved left by the number of bits specified by the right 240 i.e.,
operand. 1111 0000
>> Binary Right Shift Operator. The left operands value is A >> 2 =
moved right by the number of bits specified by the right 15 i.e.,
operand. 0000 1111
Example
Try the following example to understand all the bitwise operators available
in C −
Live Demo
#include <stdio.h>
main() {
int c = 0;
c = a | b; /* 61 = 0011 1101 */
c = a ^ b; /* 49 = 0011 0001 */
When you compile and execute the above program, it produces the
following result −
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
x = 00101000
y= 01010000
1 #include <stdio.h>
2
3 int main()
4 {
5 int m = 40,n = 80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
6 AND_opr = (m&n);
7 OR_opr = (m|n);
8 NOT_opr = (~m);
9 XOR_opr = (m^n);
10 printf("AND_opr value = %d\n",AND_opr );
11 printf("OR_opr value = %d\n",OR_opr );
12 printf("NOT_opr value = %d\n",NOT_opr );
13 printf("XOR_opr value = %d\n",XOR_opr );
14 printf("left_shift value = %d\n", m << 1);
15 printf("right_shift value = %d\n", m >> 1);
16 }
COMPILE & RUN
OUTPUT:
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20
CONTINUE ON TYPES OF C OPERATORS:
Click on each operator name below for detailed description and example programs.
it is actually refers to an object that does not have a value of any type.
functions which only print a message and have no value to return. Such a function is
used for its side effect and not for its value. In the function declaration and
definition, we have indicated that the function does not return a value by using the
data type
void
to show an empty type, i.e. no value. Similarly, when a function has no formal
parameters, the keyword
void
is used in the function prototype and header to signify that there is no information
passed to the function.
Here is a simple program using a message printing function which takes a void
void prinmsg(void);
main()
{
void printmsg(void)
{
printf("****HOME IS WHERE THE HEART IS****\n");
}
Difference Between Unicode
30.
and ASCII
Unicode vs ASCII
ASCII and Unicode are two character encodings. Basically, they are
standards on how to represent difference characters in binary so that
they can be written, stored, transmitted, and read in digital media.
The main difference between the two is in the way they encode the
character and the number of bits that they use for each. ASCII
originally used seven bits to encode each character. This was later
increased to eight with Extended ASCII to address the apparent
inadequacy of the original. In contrast, Unicode uses a variable
bit encoding program where you can choose between 32, 16, and 8-
bit encodings. Using more bits lets you use more characters at the
expense of larger files while fewer bits give you a limited choice but
you save a lot of space. Using fewer bits (i.e. UTF-8 or
ASCII) would probably be best if you are encoding a large document
in English.
One of the main reasons why Unicode was the problem arose from
the many non-standard extended ASCII programs. Unless you are
using the prevalent page, which is used by Microsoft and most
other software companies, then you are likely to encounter problems
with your characters appearing as boxes. Unicode virtually
eliminates this problem as all the character code points were
standardized.
Another major advantage of Unicode is that at its maximum it can
accommodate a huge number of characters. Because of this, Unicode
currently contains most written languages and still has room for even
more. This includes typical left-to-right scripts like English and even
right-to-left scripts like Arabic. Chinese, Japanese, and the many
other variants are also represented within Unicode. So Unicode won’t
be replaced anytime soon.
Summary:
Unicode is a standard which defines the internal text coding system in almost all
operating systems used in computers at present.Unicode assigns each character a
unique number, or code point. It defines two mapping methods, the UTF (Unicode
Transformation Format) encodings, and the UCS (Universal Character Set) encodings.
Unicode-based encodings implement the Unicode standard and include UTF-8, UTF-
16 and UTF-32/UCS-4.
UTF-8 - uses 1 byte to represent characters in the ASCII set, two bytes for characters
in several more alphabetic blocks, and three bytes for the rest of the BMP.
Supplementary characters use 4 bytes.
UTF-16 - uses 2 bytes for any character in the BMP, and 4 bytes for supplementary
characters.
Input Devices
Keyboard
The computer keyboard is used to enter text
information into the computer, as when you type the
contents of a report. The keyboard can also be used to
type commands directing the computer to perform
certain actions. Commands are typically chosen from
an on-screen menu using a mouse, but there are often
keyboard shortcuts for giving these same commands.
In addition to the keys of the main keyboard (used for PC Keyboard (you have one in
typing text), keyboards usually also have a numeric front of you that you can see for
keypad (for entering numerical data efficiently), a a closer look)
bank of editing keys (used in text editing operations),
and a row of function keys along the top (to easily
invoke certain program functions). Laptop
computers, which don’t have room for large
keyboards, often include a “fn” key so that other keys
can perform double duty (such as having a numeric
keypad function embedded within the main keyboard
keys).
Improper use or positioning of a keyboard can lead to
repetitive-stress injuries.
Some ergonomic keyboards are designed with
angled arrangements of keys and with built-in wrist
rests that can minimize your risk of RSIs.
Most keyboards attach to the PC via a PS/2 connector
or USB port (newer). Older Macintosh computers
used an ABD connector, but for several years now all
Mac keyboards have connected using USB.
Pointing Devices
The graphical user interfaces (GUIs) in use today
require some kind of device for positioning the on-
screen cursor. Typical pointing devices are: mouse,
trackball, touch pad, trackpoint, graphics tablet,
joystick, and touch screen.
Pointing devices, such as a mouse, connected to the
PC via a serial ports (old), PS/2 mouse port (newer),
or USB port (newest). Older Macs used ADB to
connect their mice, but all recent Macs
use USB (usually to a USB port right on the USB
keyboard).
Mouse
The mouse pointing device sits on your work surface
and is moved with your hand. In older mice, a ball in
the bottom of the mouse rolls on the surface as you
move the mouse, and internal rollers sense the ball
movement and transmit the information to the
computer via the cord of the mouse.
The newer optical mouse does not use a rolling ball, Two-button mouse with scroll
but instead uses a light and a small optical sensor to wheel
detect the motion of the mouse by tracking a tiny
image of the desk surface. Optical mice avoid the
problem of a dirty mouse ball, which causes regular
mice to roll unsmoothly if the mouse ball and internal
rollers are not cleaned frequently.
A cordless or wireless mouse communicates with
the computer via radio waves (often
using BlueTooth hardware and protocol) so that a
cord is not needed (but such mice need internal Wireless Macintosh mouse
batteries).
A mouse also includes one or more buttons (and
possibly a scroll wheel) to allow users to interact with
the GUI. The traditional PC mouse has two buttons,
while the traditional Macintosh mouse has one
button. On either type of computer you can also use
mice with three or more buttons and a small scroll
wheel (which can also usually be clicked like a
button).
Touch pad
Most laptop computers today have a touch
pad pointing device. You move the on-screen cursor
by sliding your finger along the surface of the touch
pad. The buttons are located below the pad, but most
touch pads allow you to perform “mouse clicks” by
tapping on the pad itself.
Touch pads have the advantage over mice that they
take up much less room to use. They have the Touch pad of a PC laptop
advantage over trackballs (which were used on early
laptops) that there are no moving parts to get dirty
and result in jumpy cursor control.
Trackpoint
Some sub-notebook computers (such as the IBM
ThinkPad), which lack room for even a touch pad,
incorporate a trackpoint, a small rubber projection
embedded between the keys of the keyboard. The
trackpoint acts like a little joystick that can be used to
control the position of the on-screen cursor.
Trackpoint
Trackball
The trackball is sort of like an upside-down mouse,
with the ball located on top. You use your fingers to
roll the trackball, and internal rollers (similar to
what’s inside a mouse) sense the motion which is
transmitted to the computer. Trackballs have the
advantage over mice in that the body of the trackball
remains stationary on your desk, so you don’t need as
much room to use the trackball. Early laptop
Trackball
computers often used trackballs (before superior
touch pads came along).
Trackballs have traditionally had the same problem as
mice: dirty rollers can make their cursor control
jumpy and unsmooth. But there are modern optical
trackballs that don’t have this problem because their
designs eliminate the rollers.
Joysticks
Joysticks and other game controllers can also be
connected to a computer as pointing devices. They are
generally used for playing games, and not for
controlling the on-screen cursor in productivity
software.
Touch screen
Some computers, especially small hand-held PDAs,
have touch sensitive display screens. The user can
make choices and press button images on the screen.
You often use a stylus, which you hold like a pen, to
“write” on the surface of a small touch screen.
Graphics tablet
A graphics tablet consists of an electronic writing area
and a special “pen” that works with it. Graphics
tablets allows artists to create graphical images with
motions and actions similar to using more traditional
drawing tools. The pen of the graphics tablet is
pressure sensitive, so pressing harder or softer can
result in brush strokes of different width (in an
appropriate graphics program).
Microphone
A microphone can be attached to a computer to
record sound (usually through a sound card input or
circuitry built into the motherboard). The sound is
digitized—turned into numbers that represent the
original analog sound waves—and stored in the
computer to later processing and playback.
MIDI Devices
MIDI (Musical Instrument Digital Interface) is
a system designed to transmit information between
electronic musical instruments. A MIDI musical
keyboard can be attached to a computer and allow a
performer to play music that is captured by the
computer system as a sequence of notes with the
associated timing (instead of recording digitized
sound waves).
Output Devices
CRT Monitor
The traditional output device of a personal computer
has been the CRT (Cathode Ray Tube) monitor. Just
like a television set (an older one, anyway) the CRT
monitor contains a large cathode ray tube that uses an
electron beam of varying strength to “paint” a picture
onto the color phosphorescent dots on the inside of
the screen. CRT monitors are heavy and use more
electrical power than flat panel displays, but they are
preferred by some graphic artists for their accurate
color rendition, and preferred by some gamers for CRT monitor
faster response to rapidly changing graphics.
Monitor screen size is measured diagonally across
the screen, in inches. Not all of the screen area may be
usable for image display, so the viewable area is also
specified. The resolutionof the monitor is the
maximum number of pixels it can display horizontally
and vertically (such as 800 x 600, or 1024 x 768, or
1600 x 1200). Most monitors can display several
resolutions below its maximum setting. Pixels (short
for picture elements) are the small dots that make of
the image displayed on the screen. The spacing of the
screen’s tiny phosphor dots is called the dot
pitch (dp), typically .28 or .26 (measured in
millimeters). A screen with a smaller dot pitch
produces sharper images.
Your computer must produce a video signal that a
monitor can display. This may be handled by circuitry
on the motherboard, but is usually handled by
a video card in one of the computer’s expansion
slots; often the slot is a special one dedicated to video
use, such as an AGP slot (Accelerated Graphics
Port). Video cards are also called video display
adapters, and graphics cards. Many video cards
contain separate processors and dedicated video
memory for generating complex graphics quickly
without burdening the CPU. These accelerated
graphics cards are loved by gamers.
Laser Printer
A laser printer produces good quality images by the
same technology that photocopiers use. A drum
coated with photosensitive material is charged, then
an image is written onto it by a laser (or LEDs) which
makes those areas lose the charge. The drum then
rolls through toner (tiny plastic particles of pigment)
that are attracted to the charged areas of the drum.
The toner is then deposited onto the paper, and then Laser Printer
fused into the paper with heat.
Most laser printers are monochrome (one color only,
usually black), but more expensive laser printers with
multiple color toner cartridges can produce color
output.
Laser printers are faster than ink jet printers. Their
speed is rated in pages per minute (ppm). Laser
printers are more expensive than ink jets, but they are
cheaper to run in the long term if you just need good
quality black & white pages.
Other Printers
Multi-function printers are available that not only
operate as a computer printer, but also include the
hardware needed to be a scanner, photocopier, and
FAX machine as well.
Dot matrix printers use small electromagnetically
activated pins in the print head, and an inked ribbon,
to produce images by impact. These printers are slow
and noisy, and are not commonly used for personal
computers anymore (but they can print multi-layer
forms, which neither ink jet or laser printers can).
Sound Output
Computers also produce sound output, ranging from
simple beeps alerting the user, to impressive game
sound effects, to concert quality music. The circuitry
to produce sound may be included on the
motherboard, but high quality audio output from a PC
usually requires a sound card in one of the
expansion slots, connected to a set of good quality
external speakers or headphones.
Multimedia is a term describing computer output
that includes sound, text, graphics, movies, and
animation. A sound card is an example of a
multimedia output device (as is a monitor that can
display graphics).
Advertisements
Previous Page
Next Page
#include <stdio.h>
if( argc == 2 ) {
else {
When the above code is compiled and executed with single argument, it
produces the following result.
$./a.out testing
When the above code is compiled and executed with a two arguments, it
produces the following result.
When the above code is compiled and executed without passing any
argument, it produces the following result.
$./a.out
One argument expected
It should be noted that argv[0] holds the name of the program itself
and argv[1] is a pointer to the first command line argument supplied, and
*argv[n] is the last argument. If no arguments are supplied, argc will be
one, and if you pass one argument then argc is set at 2.
You pass all the command line arguments separated by a space, but if
argument itself has a space then you can pass such arguments by putting
them inside double quotes "" or single quotes ''. Let us re-write above
example once again where we will print program name and we also pass
a command line argument by putting inside double quotes −
#include <stdio.h>
if( argc == 2 ) {
else {
When the above code is compiled and executed with a single argument
separated by space but inside double quotes, it produces the following
result.
$./a.out "testing1 testing2"
WP TEST
Here, TEST is a command-line argument. Your C programs may also utilize command-line
arguments. These are passed to a C program through two arguments to the main() function.
The parameters are called argc and argv. These parameters are optional and are not used
when no command-line arguments are being used.
The argc parameter holds the number of arguments on the command-line and is an integer.
It will always be at least 1 because the name of the program qualifies as the first argument.
The argv parameter is an array of string pointers. The most common method for
declaring argv is shown here.
char *argv[];
The empty brackets indicate that it is an array of undetermined length. All command-line
arguments are passed to main() as strings. To access an individual string, index argv. For
example, argv[0] points to the program's name and argv[1] points to the first argument.
This program displays all the command-line arguments that it is called with.
#include $$$$stdio.h££££
int i;
}
The ANSI C standard does not specify what constitutes a command-line argument, because
operatring systems vary considerably on this point. However, the most common convention is
as follows:
This is a test
this,that,and,another
is one string. If you need to pass a command-line argument that does, in fact contain spaces,
you must place it between quotes, as shown in this example:
"this is a test"
if (argc !=2) {
printf("Specify a password");
exit(1);
if (!strcmp(argv[1], "password"))
printf("Access Permitted");
else
printf("Access denied");
exit(1);
}
This program only allows access to its code if the correct password is entered as a command-
line argument. There are many uses for command-line arguments and they can be a powerful
tool.
My final example program takes two command-line arguments. The first is the name of a file,
the second is a character. The program searches the specified file, looking for the character.
If the file contains at least one of these characters, it reports this fact. This program
uses argv to access the file name and the character for which to search.
#include $$$$stdio.h££££
#include $$$$stdlib.h££££
char ch;
if(argc !=3) {
exit(1);
break;
fclose(fp);
[program]
The names of argv and argc are arbitrary - you can use any names you like.
However, argc and argv have traditionally been used since C's origin. It is a good idea to
use these names so that anyone reading your program can quickly identify them as
command-line parameters
1. It is used to represent multiple data items of same type by using only single
name.
2. It can be used to implement other data structures like linked lists, stacks,
queues, trees, graphs etc.
3. 2D arrays are used to represent matrices.
Disadvantages:
It allocates memory in contiguous memory locations for its elements. It does not allocate
any extra space/ memory for its elements. Hence there is no memory overflow or
shortage of memory in arrays.
Iterating the arrays using their index is faster compared to any other methods like linked
list etc.
Disadvantages
It allows us to enter only fixed number of elements into it. We cannot alter the size of the
array once array is declared. Hence if we need to insert more number of records than
declared then it is not possible. We should know array size at the compile time itself.
Inserting and deleting the records from the array would be costly since we add / delete
the elements from the array, we need to manage memory space too.
It does not verify the indexes while compiling the array. In case there is any indexes
pointed which is more than the dimension specified, then we will get run time errors
rather than identifying them at compile time.
Arrays are supported by primitive datatypes, non-primitive types like structures, unions,
pointers etc
C if...else Statement
C Programming for Loop
C Programming break and continue Statement
A prime number is a positive integer which is divisible only by 1 and itself. For
example: 2, 3, 5, 7, 11, 13
if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
return 0;
}
Output
29 is a prime number.
If the for loop terminates when the test expression of loop i <= n/2 is false, the
entered number is a prime number. The value of flag is equal to 0 in this case.
If the loop terminates because of break statement inside the if statement, the
entered number is a nonprime number. The value of flag is 1 in this case.
Visit this page to learn, how you can display all prime numbers between two intervals
entered by the user.
String reverse in C
#include <stdio.h>
#include <string.h>
int main()
{
char arr[100];
strrev(arr);
return 0;
}
#include <stdio.h>
int main()
{
char s[1000], r[1000];
int begin, end, count = 0;
printf("Input a string\n");
gets(s);
end = count - 1;
printf("%s\n", r);
return 0;
}
int main()
{
char a[100];
gets(a);
reverse(a, 0, strlen(a)-1);
printf("%s\n", a);
return 0;
}
void reverse(char *x, int begin, int end)
{
char c;
c = *(x+begin);
*(x+begin) = *(x+end);
*(x+end) = c;
#include<stdio.h>
int string_length(char*);
void reverse(char*);
main()
{
char s[100];
printf("Enter a string\n");
gets(s);
reverse(s);
return 0;
}
length = string_length(s);
begin = s;
end = s;
begin++;
end--;
}
}
return c;
}
#include<stdio.h>
int main()
{
int a, s;
printf("Enter value of a: ");
scanf("%d",&a);
s = 0;
while(a > 0)
{
s = s + (a%10);
a = a / 10;
}
printf("Sum of digits: %d",s);
return 0;
}
39. compiler
A compiler is a special program that processes statements written in a
particular programming language and turns them into machine language or
"code" that a computer's processor uses. Typically, a programmer writes
language statements in a language such as Pascal or C one line at a time
using an editor. The file that is created contains what are called the source
statements. The programmer then runs the appropriate language compiler,
specifying the name of the file that contains the source statements.
When executing (running), the compiler first parses (or analyzes) all of the
language statements syntactically one after the other and then, in one or
more successive stages or "passes", builds the output code, making sure
that statements that refer to other statements are referred to correctly in the
final code. Traditionally, the output of the compilation has been
called object code or sometimes an object module . (Note that the term
"object" here is not related to object-oriented programming.) The object
code is machine code that the processor can execute one instruction at a
time.
A compiler works with what are sometimes called 3GL and higher-level
languages. An assembler works on programs written using a processor's
assembler language.
40. C - Operators
C - Operators
Advertisements
Previous Page
Next Page
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
We will, in this chapter, look into the way each operator works.
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C
language. Assume variable A holds 10 and variable B holds 20 then −
Show Examples
Relational Operators
The following table shows all the relational operators supported by C.
Assume variable A holds 10 and variable B holds 20 then −
Show Examples
> Checks if the value of left operand is greater than the (A > B)
value of right operand. If yes, then the condition becomes is not
true. true.
< Checks if the value of left operand is less than the value of (A < B)
right operand. If yes, then the condition becomes true. is true.
>= Checks if the value of left operand is greater than or equal (A >= B)
to the value of right operand. If yes, then the condition is not
becomes true. true.
<= Checks if the value of left operand is less than or equal to (A <= B)
the value of right operand. If yes, then the condition is true.
becomes true.
Logical Operators
Following table shows all the logical operators supported by C language.
Assume variable A holds 1 and variable B holds 0, then −
Show Examples
&& Called Logical AND operator. If both the operands are non- (A && B)
zero, then the condition becomes true. is false.
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth
tables for &, |, and ^ is as follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
Show Examples
~ (~A ) = -
60, i.e,.
Binary Ones Complement Operator is unary and has the 1100 0100
effect of 'flipping' bits. in 2's
complement
form.
<< Binary Left Shift Operator. The left operands value is A << 2 =
moved left by the number of bits specified by the right 240 i.e.,
operand. 1111 0000
>> Binary Right Shift Operator. The left operands value is A >> 2 =
moved right by the number of bits specified by the right 15 i.e.,
operand. 0000 1111
Assignment Operators
The following table lists the assignment operators supported by the C
language −
Show Examples
Show Examples
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression
and decides how an expression is evaluated. Certain operators have higher
precedence than others; for example, the multiplication operator has a
higher precedence than the addition operator.
Show Examples
C Programming Operators
C programming has various operators to perform tasks including arithmetic,
conditional and bitwise operations. You will learn about various C operators and how
to use them in this tutorial.
Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Conditional Operators
Bitwise Operators
Special Operators
C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition,
subtraction and multiplication on numerical values (constants and variables).
* multiplication
/ division
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c=a/b;
printf("a/b = %d \n",c);
c=a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
It is because both variables a and b are integers. Hence, the output is also an
integer. The compiler neglects the term after decimal point and shows answer 2
instead of 2.25.
return 0;
}
Output
++a = 11
--b = 99
++c = 11.500000
++d = 99.500000
Here, the operators ++ and -- are used as prefix. These two operators can also be
used as postfix like a++ and a--. Visit this page to learn more on how increment and
decrement operators work when used as postfix.
C Assignment Operators
An assignment operator is used for assigning a value to a variable. The most
common assignment operator is =
Operator Example Same as
= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
c = a;
printf("c = %d \n", c);
c += a; // c = c+a
printf("c = %d \n", c);
c -= a; // c = c-a
printf("c = %d \n", c);
c *= a; // c = c*a
printf("c = %d \n", c);
c /= a; // c = c/a
printf("c = %d \n", c);
c %= a; // c = c%a
printf("c = %d \n", c);
return 0;
}
Output
c = 5
c = 10
c = 5
c = 25
c = 5
c = 0
C Relational Operators
A relational operator checks the relationship between two operands. If the relation is
true, it returns 1; if the relation is false, it returns value 0.
== Equal to 5 == 3 returns 0
return 0;
Output
5 == 5 = 1
5 == 10 = 0
5 > 5 = 0
5 > 10 = 0
5 < 5 = 0
5 < 10 = 1
5 != 5 = 0
5 != 10 = 1
5 >= 5 = 1
5 >= 10 = 0
5 <= 5 = 1
5 <= 10 = 1
C Logical Operators
An expression containing logical operator returns either 0 or 1 depending upon
whether expression results true or false. Logical operators are commonly used
in decision making in C programming.
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
return 0;
}
Output
(a == b) || (c < b) equals to 1
(a != b) || (c < b) equals to 0
!(a != b) equals to 1
!(a == b) equals to 0
Bitwise Operators
During computation, mathematical operations like: addition, subtraction, addition and
division are converted to bit-level which makes processing faster and saves power.
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
Other Operators
Comma Operator
Comma operators are used to link related expressions together. For example:
int a, c = 5, d;
Output
Output
Other operators such as & (reference operator), * (dereference operator) and ->
(member selection) operator will be discussed in C pointers.
42. browser
A browser is an application program that provides a way to look at and
interact with all the information on the World Wide Web. The word "browser"
seems to have originated prior to the Web as a generic term for user
interfaces that let you browse (navigate through and read) text files online.
The first Web browser, called WorldWideWeb, was created in 1990. That
browser's name was changed to Nexus to avoid confusion with the
developing information space known as the World Wide Web. The first
Web browser with a graphical user interface was Mosaic, which appeared
in 1993. Many of the user interface features in Mosaic went
into Netscape Navigator. Microsoft followed with its Internet Explorer (IE).
Firefox, which was developed from Mozilla (the open source version of
Netscape).
Flock, an open source browser based on Firefox and optimized for Web
2.0 features such as blogging and social bookmarking .
Safari, a browser for Apple computers (at this writing, the third most
popular browser).
Opera, a fast and stable browser that's compatible with most relatively
operating systems.
Primary Difference
Electronic devices have become a critical part of our lives, and people depend on them for the
purpose of collecting information and solving problems. The two most important tools in this
category are a computer and calculator that have made our lives easier. Their differences
become clearer through the definition and go as follows. A computer is usually known as a
desktop device where people have the option of using the tool for several purposes. A calculator
gets defined as a small device that performs all the basic arithmetic tasks and operations that
help people in solving complex numbers and numerical.
Advertisement
Comparison Chart
Computer Calculator
Size Bigger, that fits in a room. Smaller, that fits in the pocket.
Definition of Computer
A computer is usually known as a desktop device where people have the option of using the
tool for several purposes. It gets designed such that people get to use it for regularity and gets
placed in a single location near a desk or table due to its equipment and shape. Initially, most
of these were bigger in size and required larger tables and space to fit in. The sizes have
decreased over time, and now monitors have become slicker, the base is also smaller and more
efficient. Before the making, if a microprocessor the standard desktop device was considered
as a small unit since the original computers were enormous and required a proper room for
their working. A computer usually consists of few main items, and these include a monitor that
displays everything on the screen. A Power cable that connects the computer and the wires
with electricity to run. A keyboard that is used to input data to the computer and has numbers,
alphabets, and other keys to help to send the information. A mouse that is used to click different
items and then open them for viewing. A hard disk on which all the data gets saved and
accessed whenever it is required. A central processing unit that helps in performing all the tasks
and makes communication between the user and the computer easier. A memory that keeps
track of all the actions taken and in some cases, a printer that is used to print the data preset on
the monitor.
Advertisement
Definition of Calculator
A calculator gets defined as a small device that performs all the basic arithmetic tasks and
operations that help people in solving complicated numbers and numerical. Initially, the
devices considered as a calculator were the abacus that developed around 200 BC. Then the
mechanical calculators followed that came into existence in around 17th century. The modern
ones were drawn up in the 1970’s and came in the market parallel to the analog computers.
Different kinds of calculators are present in the market, and the most common ones provide
people with the option of doing the four basic operations that include addition, subtraction,
multiplication and division. The more complex ones have many other facilities such as solving
different matrices, arithmetic operations, geometry, theorems, probability, combination and
much more. Sizes have also changed over time, the first calculators were larger in size and had
few buttons, but now they range from pocket-size to credit card size and have many options in
buttons and others screens. The input is given through a keyboard with buttons for digits and
operations, and some also have buttons to make things simpler. Most of the simple calculators
use one button for one function, but the more excellent ones have the shift key that assigns
another task with the original button. The display shows on the screen which is smaller in size
and has a liquid-crystal display. Other kinds of the display include light-emitting diode and
vacuum fluorescent displays. It also has a memory that stores the most recent calculations and
does not have the facility f saving more data within it.
Advertisement
Differences in a Nutshell
Comparison Video
Conclusion
After reading this article, the reader will be able to develop a clear stance on how these two
devices differ from each other, what are the benefits of using them and how they get the
distinction they have gained. This task completes with relevant tables, examples, and
definitions provided along the length
UNIX and DOS-based operating systems use ASCII for text files. Windows
NT and 2000 uses a newer code, Unicode. IBM's S/390 systems use a
proprietary 8-bit code called EBCDIC. Conversion programs allow different
operating systems to change a file from one code to another.
As it says, it’s a Code, and it also explains that this Code is the American
Standard for Information Interchange.
As you may know, computers only work with HIGH(1) and LOW(0) electrical states,
known as bits, with correspond to mathematical Base 2 numbers.
Numbers are easy to store using bits, as for example, ‘8’ would be ‘1000’ at Base 2.
But graphically, you don’t have ‘8’, neither ‘0’ or ‘1’, bits in fact are just states: “On”
when powered, “Off” when not, so how could we display characters on a screen?
Skipping how they did the screen printing itself, ASCII is a Code that tells to the
display what he should print given an input.
This Code output is, internally, a byte (8 bits) that are simple regular numbers at
Base 2 (as ‘00001000’ stands for 8 at Base 10).
So what ASCII in fact is: The mapping of Binary Numbers that correspond to
Actions (that may be an action to Display a Graphical Representation of
an Character or, for example, Remove Previous Character, as does
Backspace - ASCII Code ‘00001000’)
There are many characters on Keyboard which we can type and see and many other
which can't see. Computer being a digital machine only understands and represents
Binary information. It Does not know what does character 'T' means. Inside the
computer every character is represented by a sequence of binary digits. ASCII is a
character representation scheme based on 7 bits. That is, every character in this
scheme can be represented as a unique combination of 7 binary digits. ASCII table tell
us what is the binary sequence against any character that we are familiar of. for
example 'a' has its own binary sequence representation which is 01100001 (97 in
decimal) and so on. because of it's seven bits limitation it can only represent 128
unique characters. some other character sets also exist which uses more bit and hence
capable of representing even every possible character that exists in any language in the
world e.g extended ASCII table and Unicode which is among one of the most famous
Two-dimensional Arrays
The simplest form of multidimensional array is the two-dimensional array.
A two-dimensional array is, in essence, a list of one-dimensional arrays.
To declare a two-dimensional integer array of size [x][y], you would write
something as follows −
type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid
C identifier. A two-dimensional array can be considered as a table which
will have x number of rows and y number of columns. A two-dimensional
array a, which contains three rows and four columns can be shown as
follows −
int a[3][4] = {
The nested braces, which indicate the intended row, are optional. The
following initialization is equivalent to the previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
The above statement will take the 4th element from the 3rd row of the
array. You can verify it in the above figure. Let us check the following
program where we have used a nested loop to handle a two-dimensional
array −
Live Demo
#include <stdio.h>
int main () {
int i, j;
}
return 0;
When the above code is compiled and executed, it produces the following
result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions,
although it is likely that most of the arrays you create will be of one or two
dimensions.
C Programming Multidimensional
Arrays
In this article, you will learn to work with multidimensional arrays (two
dimensional and three dimensional array).
In C programming, you can create an array of arrays known as multidimensional
array. For example,
float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can
think the array as table with 3 row and each row has 4 column.
Similarly, you can declare a three-dimensional (3d) array. For example,
float y[2][4][3];
You can think this example as: Each 2 elements have 4 elements, which makes 8
elements and each 8 elements can have 3 elements. Hence, the total number of
elements is 24.
Above code are three different ways to initialize a two dimensional arrays.
};
int main()
{
int temperature[CITY][WEEK];
for (int i = 0; i < CITY; ++i) {
for(int j = 0; j < WEEK; ++j) {
printf("City %d, Day %d: ", i+1, j+1);
scanf("%d", &temperature[i][j]);
}
}
Output
City 1, Day 1: 33
City 1, Day 2: 34
City 1, Day 3: 35
City 1, Day 4: 33
City 1, Day 5: 32
City 1, Day 6: 31
City 1, Day 7: 30
City 2, Day 1: 23
City 2, Day 2: 22
City 2, Day 3: 21
City 2, Day 4: 24
City 2, Day 5: 22
City 2, Day 6: 25
City 2, Day 7: 26
Displaying values:
City 1, Day 1 = 33
City 1, Day 2 = 34
City 1, Day 3 = 35
City 1, Day 4 = 33
City 1, Day 5 = 32
City 1, Day 6 = 31
City 1, Day 7 = 30
City 2, Day 1 = 23
City 2, Day 2 = 22
City 2, Day 3 = 21
City 2, Day 4 = 24
City 2, Day 5 = 22
City 2, Day 6 = 25
City 2, Day 7 = 26
#include <stdio.h>
int main()
{
float a[2][2], b[2][2], c[2][2];
int i, j;
if(j==1)
printf("\n");
}
return 0;
}
Ouput
Enter a11: 2;
Enter a22: 2;
Enter b12: 0;
Sum Of Matrix:
2.2 0.5
-0.9 25.0
Example 3: Three Dimensional Array
C Program to store values entered by the user in a three-dimensional array
and display it.
#include <stdio.h>
int main()
{
// this array can store 12 elements
int i, j, k, test[2][3][2];
printf("\nDisplaying values:\n");
Output
Enter 12 values:
10
11
12
Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12