0% found this document useful (0 votes)
8 views5 pages

S2 C PRGRM

The document provides an overview of computer architecture, detailing the types of memory, the role of the CPU, and the different programming languages. It explains the functions of primary and secondary memory, registers, and the arithmetic logic unit, along with algorithms for various mathematical operations. Additionally, it covers programming concepts such as operators, keywords, and pseudocode examples for common tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views5 pages

S2 C PRGRM

The document provides an overview of computer architecture, detailing the types of memory, the role of the CPU, and the different programming languages. It explains the functions of primary and secondary memory, registers, and the arithmetic logic unit, along with algorithms for various mathematical operations. Additionally, it covers programming concepts such as operators, keywords, and pseudocode examples for common tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Computer architecture Anything and everything in a TYPES OF LANGUAGES and is based on abbreviations Algorithm to find the area of circle

computer is stored in the form of Computer programs can be written (called mnemonics) that help the 1. Start
bits known as binary language or in high and low level languages, programmer remember individual 2. Read radius
machine language. 8 bits make up a depending on the task and the instructions, registers, etc. Small, 3. area=3.14*radius*radius
byte. The total number of bytes hardware being used. English-like representation is used 4. Print area
that a memory chip can hold at a LOW LEVEL LANGUAGE (MACHINE to write the program in assembly 5. Stop
time is termed as its size or LANGUAGE) language Features. Assembly Algorithm to find the sum of two
capacity. Information is stored and A program written in machine language programs are easier to numbers
processed as a group of bytes, language is a collection of binary write than the machine language 1. Start
called computer word. The word digits or bits ( 0 and 1) that the programs, since assembly language 2. Read a, b
length is specific for each computer reads and interprets. programs use short, English-like 3. Sum=a+b
processor. Features. The computer can representation of machine code. 4. Print Sum
The Registers - Since the group of understand the programs written For example 5. Stop
registers is in-built within the in machine language directly. No ADD 2, 3 Algorithm to find the greatest of
processor chip, they are the fastest translation of the program is LOAD A three given numbers
accessible units of memory by the needed. Program written in SUB A, B 1. Start
processor. They are highly machine language can be executed HIGH LEVEL LANGUAGE 2. Read three numbers to a,b and c
expensive and hence are limited in very fast (Since no translation is High level languages are written in 3. Check whether ‘a’ is greater than
number. Some registers are used to required). Machine language is a form that is close to human ‘b’; if so, goto step 5 (Else control
store data while some are defined by the hardware of a language, enabling the automatically goes to the step 4)
reserved to store address. There computer. It depends on the type programmer to just focus on the 4. Check whether ‘b’ is greater than
are some general purpose registers of the processor or processor problem being solved. ‘c’; if so display ‘b’ as the greatest
as well. Size of the registers family that the computer uses, and Features. Programs are easier to number and goto step 5 ; else
depends on the processor. is thus machine-dependent. A write, read or understand in high- display ‘c’ as the greatest number
Accumulator is a register found on machine- level program written on level languages. Programs written and goto step 5
all processors, which is mainly used one computer may not work on in high-level languages is the 5. Check whether ‘a’ is greater than
to store the operand of an another computer with a different source code which is converted ‘c’; if so display ‘a’ as the greatest
arithmetic operation. Program processor into the object code (machine number else display ‘c’ as the
Central Processing Unit (CPU) counter (PC) always stores the ASSEMBLY LANGUAGE code) using translator software like greatest number
CPU is the brain of the computer address of the next instruction to A program written in assembly interpreter or compiler. A line of 6. Stop
system. All major calculation and be executed by the processor. language uses symbolic code in high-level program may Algorithm to find the average of N
comparisons are made inside the Primary Memory: - The memory representation of machine codes correspond to more than one line numbers
CPU and it is also responsible for chips that the processor can needed to program a particular of machine code. Programs written 1. Start
activation and controlling the directly access are referred to as processor (CPU) or processor in high-level languages are easily 2. Sum=0, Count=0
operation of other units. This unit primary memory. The three types family. This representation is portable from one computer to 3. Read N
consists of two major components of primary memory are RAM, ROM usually defined by the CPU another. Example: C, C++, Java, 4. Read Num
that are arithmetic logic unit (ALU) and CMOS. RAM is volatile whereas manufacturer, python 5. Sum=Sum+Num
and control unit (CU). ROM as CMOS are non-volatile 6. Count=Count+1
Arithmetic Logic Unit (ALU) memories. They are metal oxide 7. If Count<N , then goto step 4
Arithmetic logic unit performs all semiconductor memory cells built 8. Average=Sum/N
arithmetic operations such as on silicon based ICs. 9. Print Average
addition, subtraction,multiplication Random Access Memory (RAM): 10. Stop
and division. It also uses logic RAM is a volatile memory and loses Algorithm to find the largest of N
operation for comparison. its contents when the power is numbers
Control Unit (CU) turned off. The circuit is so 1. Start
The control unit of a CPU controls designed that any random location 2. Count=0
the entire operation of the can be directly accessed without 3. Read N
computer. It also controls all the need to scroll up or down the 4. Read Num
devices such as memory, I / o memory. The program to be 5. Large=Num
devices connected to the CPU. executed is loaded into RAM from 6. Read Num
Additionally, CPU also has a set of the non-volatile backup memory. 7. If Num>Large, then Large=Num
registers for temporary storage of The processor reads instructions 8. Count=Count+1
data, instructions, addresses and and data from the RAM, executes 9. If Count<N-1, then goto step 6
intermediate results of calculation, them and writes data back to the 10. Print Large
When the ALU, CU and the RAM. Hence RAM is also known as 11. Stop
registers are all integrated on a the main memory of the computer. Algorithm for bubble sort
single chip, it is called a Everything from the RAM is copied 1. Start
microprocessor thereby capturing to the non-volatile backup memory 2. Get the total number of
the entire CPU on a single chip before the computer is turned off. elements of the array in variable,
Input /Output Unit The two main types of RAM are ‘n’
The input/output unit consists of Dynamic Ram (DRAM) and static 3. Read the numbers into array a
devices used to transmit RAM (SRAM) 4. Let i=0
information between the The Cache Memory: - It is a small 5. Let j=0
external world and computer piece of high speed volatile 6. Compare jth number with the
memory. The information fed memory located closer to the (j+1)th number; if it is greater,
through the input unit is stored processor for fast processing. swap them
in computer's memory for Cache memory is made of high 7. Increment j
processing and the final result speed SRAMs. It acts as a buffer 8. Repeat step 6 & 7 until j= n-i-1
stored in memory can be between the CPU and the RAM. It 9. Increment i
recorded or displayed on the holds frequently accessed data and 10. Repeat steps 5 to 9 until i=n-1
output medium. instructions so that they can be 11. Print the sorted array
Examples for input devices: Mouse, easily supplied to the CPU when 12. Stop
Keyboard, Scanner, Joy Stick, requested again. Cache memory is Algorithm for linear search
Microphone, OCR (Optical used to reduce the average time to 1. Start
Character Reader), MICR (Magnetic access data from the Main 2. Get the total number of
Ink Character Reader) memory. elements of the array in variable,
Examples for output devices: Secondary Memory: - Primary ‘n’
Printer (Dot Matrix, Ink Jet, Laser, memory has limited storage 3. Read the numbers into array a
Line), Monitor capacity and is volatile. Secondary 4. Read the number to be searched
Memory Unit memory overcomes this limitation in x
The Memory unit refers to the area by providing permanent storage of 5. Set flag as 0
where instructions and data are data and in bulk quantity. They are 6. Let i=0
stored in a computer. The the slowest and cheapest form of Pseudocode to find the area of print: a is the greatest /* a>b and 7. Check whether ith element of a
processor reads instructions and memory. It cannot be accessed circle a>c, so a is the greatest is equal to x; if yes, set flag as 1 and
data from the memory, executes directly by the CPU. Programs need 1. START else goto step 10
them and writes the result back to to be moved to primary memory in 2. Read radius print: c is the greatest /* a>b but 8. Increment i
it. Different forms of memory are order to be executed by the CPU. 3. area = 3.14 * radius * radius a<c which implies c is the greatest 9. Repeat step 7 & 8 until i= n-1
used in a computer system. They Secondary memory is also termed 4. print area 5. STOP */ 10. If flag is 1, print “the element is
vary in their size, speed and as external memory and refers to Pseudocode to find the greatest of elseif b>c found at position i+1”; else print
location. the various storage media on which 3 numbers print: b is the greatest /* a<b and “element not found”
a computer can store data and int a, b, c b>c then b is the greatest */ 11. Stop
programs example :- floppy disk, print: enter the numbers else
hard disk, pendrive, compact disk scan: a, b, c print: c is the greatest /* a<b and
if a>b b<c which implies c is the greatest
if a>c */
TOKEN OPERATORS i. “=”:This operator is used to assign the BRANCHING STATEMENTS Program to read nos. b/w 1 and 7
Every C program is a collection of 1. ARITHMETIC OPERATORS value on the right to the variable on the 1) if statement and display the day Corresponding
instructions and every instruction is These are the operators used to perform left. For example: a = 10; Syntax to the no. (using switch fn)
a collection of some individual arithmetic/mathematical operations on ii. “+=”: This operator is combination of ‘+’ • if #include <stdio.h>
units. Every smallest individual unit operands. and ‘=’ operators. This operator first adds if (expression) { void main() {
of a c program is called token. + Addition the current value of the variable on left to Statement(s); } int n;
Every instruction in a c program is a - Subtraction the value on right and then assigns the • if—else printf("Enter the value of n");
collection of tokens * Multiplication result to the variable on the left. Example: if (expression) { scanf("%d",&n);
Keywords / Division (a += b) can be written as (a = a + b) If Statements; } switch(n) {
Keywords are specific reserved % Modular Division initially value stored in a is 5. Then (a += Else { case 1: printf("\nSunday");
words in C each of which has a Arithmetic operators are of two types: 6) = 11. Statements; } break;
specific feature associated with it. I. Unary Operators: Operators that iii. “-=”: This operator is combination of ‘- • if—else if case 2: printf("\nMonday");
Keywords are always in lowercase. operates or works with a single operand ‘and ‘=’ operators. This operator first if (expression) { break;
There are total of 32 keywords in C: are unary operators. For example: (++ , –) subtracts the value on right from the Statements; } case 3: printf("\nTuesday");
Auto, break, case, char, const, II. Binary Operators: Operators that current value of the variable on left and else if(expression) { break;
continue etc operates or works with two operands are then assigns the result to the variable on Statements; } case 4: printf("\nWednesday");
Identifier binary operators. For example: (+ , – , * , the left. Example: (a -= b) can be written else if(expression) { break;
An identifier is a collection of /,%) as (a = a - b) If initially value stored in a is Statements; } case 5: printf("\nThursday");
characters which acts as the name 2. RELATIONAL OPERATORS 8. Then (a -= 6) = 2. ……………………… break;
of variable, function, array, pointer, These are used for comparison of the iv. “*=”: This operator is combination of ………………………. case 6: printf("\nFriday");
structure, etc. values of two operands. ‘*’ and ‘=’ operators. This operator first Else { break;
Rules for Creating a Valid Identifier 1. Equal to operator: Represented as ‘==’, multiplies the current value of the Statements; } case 7: printf("\nSaturday");
1. An identifier can contain letters the equal to operator checks whether the variable on left to the value on right and • Nested if break;
(Upper case and lower case), digit two given operands are equal or not. If so, then assigns the result to the variable on It is possible to include if...else default:printf("\nWrong Choice");}}
and underscore symbol only. it returns 1. Otherwise it returns 0. For the left. Example: (a *= b) can be written statement(s) inside the body of Program to read a no. and find the
2. An identifier should not start example, 5==5 will return 1. as (a = a * b) If initially value stored in a is another if...else statement reverse of the no. (while loop)
with a digit value. It can start with a 2. Not equal to operator: Represented as 5. Then (a *= 6) = 30. if(condition1) { #include <stdio.h>
letter or an underscore. ‘!=’, the not equal to operator checks v. “/=”: This operator is combination of ‘/’ if(condition2) { void main() {
3. Should not use any special whether the two given operands are and ‘=’ operators. This operator first statement1; } int n,rev=0,digit;
symbols in between the identifier equal or not. If not, it returns 1. divides the current value of the variable else { printf("Enter the number:");
even whitespace. Otherwise it returns 0. It is the exact on left by the value on right and then statement2; } } scanf("%d",&n);
4. Keywords should not be used as boolean complement of the ‘==’ operator. assigns the result to the variable on the else { while ( n > 0 ) {
identifiers. For example, 5!=5 will return 0. left. Example: (a /= b) can be written as (a statement3; } digit = n%10;
5. There is no limit for the length of 3. Greater than operator: Represented as = a / b) If initially value stored in a is 6. rev = rev * 10 + digit;
an identifier. However, the ‘>’, the greater than operator checks Then (a /= 2) = 3. Program to check whether a n = n/10; }
compiler considers the first 31 whether the first operand is greater than 5. BITWISE OPERATORS number is even or odd. printf("\nReverse = %d",rev); }
characters only. the second operand or not. If so, it The Bitwise operators are used to #include <stdio.h> Program to read a no. & check
6. In C language, the identifiers are returns 1. Otherwise it returns 0. For perform bit-level operations on the void main() { whether it is palindrome / not.
case sensitive example, 6>5 will return 1. operands. The operators are first int n; #include <stdio.h>
DATA TYPES 4. Less than operator: Represented as ‘<‘, converted to bit-level and then the printf("Enter the value of n:"); void main() {
Data types in the c programming the less than operator checks whether the calculation is performed on the operands. scanf("%d",&n); int n,rev=0,digit,org;
language are used to specify what first operand is lesser than the second The mathematical operations such as if( n%2 == 0) printf("Enter the number:");
kind of value can be stored in a operand. If so, it returns 1. Otherwise it addition, subtraction, multiplication etc. printf(“\n Even”); scanf("%d",&n);
variable. The memory size and type returns 0. For example, 6<5 will return 0 can be performed at bit-level for faster else org=n;
of the value of avariable are 5. Greater than or equal to operator: processing. printf(“\nOdd”); } while ( n > 0 ) {
determined by the variable data Represented as ‘>=’, the greater than or 1. & (bitwise AND) in C takes two Program to check whether a no. is digit = n%10;
type. equal to operator checks whether the first numbers as operands and does AND on negative or positive or zero. rev = rev * 10 + digit;
In the C programming language, operand is greater than or equal to the every bit of two numbers. The result of #include <stdio.h> n = n/10; }
data types are classified as follows second operand. If so, it returns 1 else it AND is 1 only if both bits are 1. void main() { if( org == rev) {
1. Primary data types (Basic data returns 0. For example, 5>=5 will 2. | (bitwise OR) in C takes two numbers int n; printf("Palindrome"); }
types OR Predefined data types) return 1. as operands and does OR on every bit of printf("Enter the value of n:"); else {
2. Derived data types (Secondary 6. Less than or equal to operator: two numbers. The result of OR is 1 if any scanf("%d",&n); printf("Not Palindrome"); } }
data types OR User-defined data Represented as ‘<=’, the less than or of the two bits is 1. if( n > 0) { Program to read a no. & check
types) equal to operator checks whether the first 3. ^ (bitwise XOR) in C takes two numbers printf("\nPositive"); } whether a no. is Armstrong or not.
VARIABLES operand is less than or equal to the as operands and does XOR on every bit of else if(n < 0) { #include <stdio.h>
A variable is an identifier that is second operand. If so, it returns 1 else 0. two numbers. The result of XOR is 1 if the printf("\nNegative"); } #include <math.h>
used to represent some specified For example, 5<=5 will also return 1 two bits are different. else { void main() {
type of information within a 3. LOGICAL OPERATORS 4. << (left shift) in C takes two numbers, printf("\nZero"); } int n,sum=0,temp,org,count=0;
designated portion of the program. They are used to combine two or more left shifts the bits of the first operand, the Program to find largest of 2 nos. printf("Enter the number:");
Variables in a c programming conditions/constraints or to complement second operand decides the number of #include <stdio.h> scanf("%d",&n);
language are the named memory the evaluation of the original condition places to shift. void main() { org=n;
locations where the user can store under consideration. They are described 5. >> (right shift) in C takes two numbers, int a,b; while( n > 0) {
different values of the same below: right shifts the bits of the first operand, printf("Enter the value of a and count++;
datatype during the program Logical AND operator: The ‘&&’operator the second operand decides the number b:"); n=n/10; }
execution. returns 1 when both the conditions under of places to shift. scanf("%d%d",&a,&b); while ( n > 0 ) {
CONSTANTS consideration are satisfied. Otherwise it 6. ~ (bitwise NOT) in C takes one number if(a>b) { temp = n%10;
A constant is a value or variable returns 0. For example, a && b returns 1 and inverts all bits of it. printf("\n%d is larger than rev = sum + pow(temp,count);
that can't be changed in the when both a and b are 1 (i.e. non-zero). 6. CONDITIONAL OPERATOR %d",a,b); } n = n/10; }
program, for example: 10, 20, 'a', Logical OR operator: The ‘||’ operator Conditional operator is a ternary else { if( org == sum) {
3.4, "c programming" etc. returns 1 even if one (or both) of the operator. Conditional operator is of the printf("\n%d is larger than printf("\nArmstrong"); }
conditions under consideration is form %d",b,a); } } else {
Switch statement satisfied. Otherwise it returns 0. For Expression1 ? Expression2 : Expression3 . Program check whether n is even printf("\nNot Armstrong"); } }
The switch statement is much like a example, a || b returns 1 if one of a or b Here, Expression1 is the condition to be or odd using AND operator. Program to find sum of first n
nested if .. else statement. switch or both are 1 (i.e. non-zero). Of course, it evaluated. If the condition(Expression1) is #include <stdio.h> natural numbers. (for loop)
statement can be slightly more returns 1 when both a and b are 1. True then we will execute and return the void main() { #include <stdio.h>
efficient and easier to read. Logical NOT operator: The ‘!’ operator result of Expression2 otherwise if the int n; void main() {
Syntax returns 1 the condition in consideration is condition(Expression1) is false then we printf("Enter the value of n:"); int n,i,sum=0;
switch( expression ) { not satisfied. Otherwise it returns 0. For will execute and return the result of scanf("%d",&n); printf("Enter the value of n:");
case constant-expression1: example, !a returns 1 if a is 0, i.e. when Expression3. We may replace the use of if( n & 1 == 0) { scanf("%d",&n);
statements1; a=0 if..else statements by conditional printf("\nEven"); } for(i=1;i<=n;i++) {
break; 4. ASSIGNMENT OPERATORS operators. else { sum = sum + i; }
case constant-expression2: Assignment operators are used to assign Largest of two numbers using conditional printf("\nOdd"); } } printf("\nSum = %d",sum); }
statements2; value to a variable. The left side operand operator (ternary operator) Program to read a nos. and find Program to find the factorial of a
break; of the assignment operator is a variable #include<stdio.h> sum of digits of a nos. (while loop) number. (for loop)
case constant-expression3: and right side operand of the assignment void main() #include <stdio.h> #include <stdio.h>
statements3; operator is a value. The value on the right { void main() { void main() {
break; default : statements4; } side must be of the same data-type of int a,b,large; int n,sum=0,temp; int n,i,fact=1;
variable on the left side otherwise printf("Enter the value of a and b"); printf("Enter the number:"); printf("Enter the value of n:");
the compiler will raise an error. scanf("%d%d",&a,&b); scanf("%d",&n); scanf("%d",&n);
Different types of assignment operators large = a>b ? a : b; while ( n > 0 ) { for(i=1;i<=n;i++) {
are shown below: printf("Largest=%d\n",large); temp = n%10; fact = fact * i; }
sum = sum + temp; printf("\nFactorial = %d",fact); }
n = n/10; }
printf("\nSum = %d",sum); }
JUMP STATEMENTS Program to read and display an LINEAR SEARCH Program to check whether a string MODULAR PROGRAMMING
1) BREAK STATEMENT array of size n. Algorithm is palindrome or not without using Modular programming is the
Break statement is used to bring #include<stdio.h> Linear Search (Array A, Value x) in built functions. process of subdividing a computer
the program control out of the void main() { Step 1: Set i to 0 #include<stdio.h> program into separate sub-
loop. The break statement is used int n,A[20],i; Step 2: if i = n-1 then go to step 7 #include<string.h> programs. It is a software design
inside loops or switch statement. printf("Enter the size of Array:"); Step 3: if A[i] = x then go to step 6 void main() { technique that emphasizes
Example scanf("%d",&n); Step 4: Set i to i + 1 char str[20]; separating the functionality of a
#include<stdio.h> for(i=0;i<n;i++) { Step 5: Go to Step 2 int len,i,j,flag; program into independent,
void main () { printf("\nEnter the number:"); Step 6: Print Element x Found at printf("Enter the string:"); interchangeable modules, such that
int i; scanf("%d",&A[i]); } index i and go to step 8 gets(str); each contains everything necessary
for(i = 0; i<10; i++) { for(i=0;i<n;i++) { Step 7: Print element not found for(len=0;str[len]!='\0';len++); to execute only one aspect of the
printf("%d\t ",i); printf("%d\t",A[i]); } } Step 8: Exit flag=0; desired functionality.
if(i == 5) Program to find sum and average Program to search an element in for(i=0;i<len/2;i++) { Advantages
break; } of an array of size n. an array of size n.(linear search) if(str[i] != str[len-i-1]) { Ease of Use :This approach allows
printf("\n Came out with i = %d",i);} #include<stdio.h> #include<stdio.h> flag=1; simplicity, as rather than focusing
2) CONTINUE STATEMENT void main() { void main() { break; } } on the entire thousands and
The continue statement is used int n,A[20],i,sum; float avg; int n,A[20],i,pos=-1; if(flag == 0) { millions of lines code in one go, we
inside loops. When a continue printf("Enter the size of Array:"); printf("Enter the size of Array:"); printf("\nPalindrome"); } can access it in the form of
statement is encountered inside a scanf("%d",&n); scanf("%d",&n); else { modules.
loop, control jumps to the for(i=0;i<n;i++) { for(i=0;i<n;i++) { printf("\nNot Palindrome"); } } Programming errors are easy to
beginning of the loop for next printf("\nEnter the number"); printf("\nEnter the number:"); detect: Minimizes the risks of
iteration, skipping the execution of scanf("%d",&A[i]); } scanf("%d",&A[i]); } TWO DIMENSIONAL ARRAY ending up with programming errors
statements inside the body of loop sum=0; printf("\nEnter the element to An array of arrays is known as 2D and also makes it easier to spot
for the current iteration. for(i=0;i<n;i++) { search"); array. The two dimensional (2D) errors, if any.
Example sum = sum + A[i]; } scanf("%d",&key); array is also known as matrix
#include <stdio.h> avg = (float)sum/n; for(i=0;i<n;i++) { INITIALIZATION OF TWO FUNCTION
void main() { printf("\nSum=%d",sum); if(A[i] == key) { DIMENSIONAL ARRAY A function is a group of statements
int i; printf("\nAverage=%f",avg); } pos= i; There are two ways to initialize a that together perform a task. Every
for (i=0; i<=8; i++) { Program to read and display even break; } } two Dimensional arrays during C program has at least one
if (i==4) { numbers in an array of size n. if(pos == -1) { declaration. function, which is main(), and can
continue; } #include<stdio.h> printf("\nElement not found"); } 1. int A[2][3] = { {10, 11, 12},{14, 15, have additional functions.
printf("%d\t ",i); } } void main() { else { 16}}; Types of Functions
3) GOTO STATEMENT int n,A[20],i; prinf("\nElement found at index int A[][3] = { {10, 11, 12},{14, 15, STANDARD LIBRARY FUNCTIONS
(UNCONDITIONAL JUMP) printf("Enter the size of Array:"); %d",pos); } } 16}}; The standard library functions are
The goto statement allows us to scanf("%d",&n); 2. int A[2][3] = { 10, 11, 12, 14, 15, built-in functions in C
transfer control of the program to for(i=0;i<n;i++) { Bubble sort 16}; programming. These functions are
the specified label. printf("\nEnter the number:"); Program to sort the elements in an int A[][3] = { 10, 11, 12, 14, 15, 16}; defined in header files. For
Syntax scanf("%d",&A[i]); } array of size n.(BUBBLE SORT) Program to read a matrix of size example,
goto label; printf(“\nEven Numbers are\t”); #include<stdio.h> mXn and display its transpose. The printf() is a standard library
... .. ... for(i=0;i<n;i++) { void main() { #include<stdio.h> function to send formatted output
... .. ... if(A[i]%2 == 0) int n,A[20],i,j,temp; void main() { to the screen (display output on
label: printf("%d\t",A[i]); } } printf("Enter the size of Array"); int m,n,A[20][20],i,j; the screen). This function is defined
statement; Program to read and display prime scanf("%d",&n); printf("Enter the order of matrix:"); in the stdio.h header file.
Program to read a no. and check numbers in an array of size n. for(i=0;i<n;i++) { scanf("%d%d",&m,&n); The sqrt() function calculates the
whether a no. is odd or even. #include<stdio.h> printf("\nEnter the number:"); for(i=0;i<m;i++) { square root of a number. The
#include <stdio.h> #include<math.h> scanf("%d",&A[i]); } for(j=0;j<n;j++) { function is defined in the math.h
void main() { void main() { printf("Before Sorting"); printf("Enter the element:"); header file.
int n; int n,A[20],i,flag,j; for(i=0;i<n;i++) { scanf("%d",&A[i][j]); } } The strlen() function calculates
printf("Enter the value of n:"); printf("Enter the size of Array:"); printf("%d\t",A[i]); } printf(“\nTranspose of Matrix\n”); the length of a given string. The
scanf("%d",&n); scanf("%d",&n); for(i=0;i<n-1;i++) { for(j=0;j<n;j++) { function is defined in the string.h
if(n % 2 ==0) for(i=0;i<n;i++) { for(j=0;j<n-i-1;j++) { for(i=0;i<m;i++) { header file.
goto EVEN; printf("\nEnter the number:"); if(A[j]>A[j+1]) { printf("%d\t",A[i][j]) } USER-DEFINED FUNCTIONS
else scanf("%d",&A[i]); } temp=A[j]; printf("\n"); } } Functions that we define ourselves
goto ODD; printf(“\nPrime Numbers are\t”); A[j]=A[j+1]; Program to multiply two matrices to do certain specific task are
EVEN:printf("\nEven"); for(i=0;i<n;i++) { A[j+1]=temp; } } } To multiply two matrices, the referred as user- defined functions.
ODD: printf("\nOdd"); } flag=0; printf("\nAfter Sorting \t"); number of columns of the first Advantages of user-defined
for(j=2;j<=sqrt(A[i]);j++) { for(i=0;i<n;i++) { matrix should be equal to the functions
ARRAY if(A[i]%j == 0) { printf("%d\t",A[i]); } } number of rows of the second The program will be easier to
An array in C is a collection of items flag=1; Program to concatenate 2 strings matrix. understand, maintain and debug.
stored at contiguous memory break; } } without using string handling fnctn #include <stdio.h> Reusable codes that can be used
locations and elements can be if(flag == 0) { #include <stdio.h> void main() { in other programs
accessed randomly using indices of printf("%d\t",A[i]); } } } void main() { int i,j,k,m, n, p, q,sum = 0; A large program can be divided
an array. They are used to store Program to find largest element in char str1[50], str2[25], i, j; int A[10][10], B[10][10], C[10][10]; into smaller modules. Hence, a
similar type (homogeneous) of an array of size n. printf("\nEnter first string: "); printf("Enter number of rows and large project can be divided among
elements as the data type must be #include<stdio.h> gets(str1); columns of first matrix\n"); many programmers
the same for all elements. They can void main() { printf("\nEnter second string: "); scanf("%d%d", &m, &n); Function Definition
be used to store collection of int n,A[20],i,large; gets(str2); printf("Enter number of rows and A function definition in C
primitive data types such as int, printf("Enter the size of Array:"); for(i=0; str1[i]!='\0'; i++); columns of second matrix\n"); programming consists of a function
float, double, char, etc of any scanf("%d",&n); for(j=0; str2[j]!='\0'; j++, i++) { scanf("%d%d", &p, &q); header and a function body.
particular type. for(i=0;i<n;i++) { str1[i]=str2[j]; } if (n != p) Function header consist of return
Different ways of declaring an printf("\nEnter the number"); str1[i]='\0'; printf("The multiplication isn't type,function
Array scanf("%d",&A[i]); } printf("\nOutput: %s",str1); } possible.\n"); name,arguments(parameters).
1. Array declaration by specifying large=A[0]; Program to copy a string to else { Return Type: A function may
size Eg: int A[10]; for(i=1;i<n;i++) { another without using string printf("Enter elements of first return a value. The return_type is
2. Array declaration by initializing if(large < A[i]) handling function matrix\n"); the data type of the value the
elements large = A[i] } #include<stdio.h> for (i = 0; i < m; i++) function returns. Some functions
Eg: int A[] = { 10, 20, 30, 40 }; printf("\nLarge =%d",large); } void main() { for (j = 0; j < n; j++) perform the desired operations
3. Array declaration by specifying char a[50], b[50]; scanf("%d", &A[i][j]); without returning a value. In this
size and initializing elements IN-BUILT STRING FUNCTIONS int i=0; printf("Enter elements of second case, the return_type is the
Eg: int A[6] = { 10, 20, 30, 40 }; strlen() = computes string's length printf(“Enter string1:”); matrix\n"); keyword void
Advantages of an Array strcpy() = copies a string to another gets(a); for (i = 0; i < p; i++) Function Name: The actual name
1. Random access of elements strcat() = concatenates(joins) two for(i=0;a[i]!=‘\0’;i++) { for (j = 0; j < q; j++) of the function. The function name
using array index. strings b[i]=a[i]; } scanf("%d", &B[i][j]); and the parameter list together
2. Use of less line of code as it strcmp() = compares two strings b[i]=‘\0’; } for (i= 0; i < m; i++) { constitute the function signature.
creates a single array of multiple case sensitive checking for (j = 0; j < q; j++) { Parameters: A parameter is like a
elements. strcmpi() = compares two strings C[i][j]=0; placeholder. When a function is
3. Easy access to all the elements. case insensitive checking for (k = 0; k < p; k++) { invoked, you pass a value to the
4. Traversal through the array strlwr() = converts string to C[i][j]= C[i][j] + A[i][k]*B[k][j]; } } } parameter. Parameters are
becomes easy using a single loop. lowercase printf("Product of the optional; that is, a function may
5. Sorting becomes easy as it can strupr() = converts string to matrices:\n"); contain no parameters.
be accomplished by writing less line uppercase for (i = 0; i< m; i++) { Function Body: The function body
of code. for (j = 0; j< q; j++) { contains a collection of statements
printf("%d\t", C[i][j]); } that define what the function does
printf("\n"); } }}
Formal and Actual Parameters TYPES OF USER DEFINED RECURSIVE FUNCTION STRUCTURE POINTER TO POINTER
There are different ways in which FUNCTIONS In some problems, it may be A structure is a user defined data A pointer points to an address of
parameters can be passed into and Functions with no arguments natural to define the problem in type in C. A Structure is a collection another pointer. Such pointers are
out of functions. Let us assume that and no return values terms of the problem itself. of related data items, possibly of known as pointer to pointer or
a function B() is called from // function to read two numbers Recursion is useful for problems different types. A Structure is double pointers.
another function A(). In this and print its sum that can be represented by a heterogeneous in that it can be Example
case A is called the “caller function” void add() { simpler version of the same composed of data of different #include<stdio.h>
and B is called the “called function int a,b,sum; problem. types. In contrast, array is void main() {
or callee function”. Also, the printf("Enter the values of a & b"); Example: the factorial function homogeneous since it can contain int a=10;
arguments which A sends to B are scanf("%d%d",&a,&b); 6! = 6 * 5 * 4 * 3 * 2 * 1 only data of the same type.The int *p,**q;
called actual arguments and the sum = a+b; We could write: keyword ‘struct’ is used to create a p=&a;
parameters of B are called formal printf("Sum=%d",sum); } 6! = 6 * 5! structure. A structure variable can q=&p;
arguments. Functions with arguments and Program to find factorial of a either be declared with structure printf("\nValue of a is %d \n",a);
Formal Parameter: A variable and no return values number using recursive function declaration or as a separate printf("\nValue of *p is %d \n",*p);
its type as they appear in the // function that takes two #include<stdio.h> declaration like basic types. printf("\nValue of **q is %d \n
prototype of the function or arguments and print their sum. int fact(int n) { Program to create a structure ",**q); }
method. void add(int a,int b) { if( n == 0) employee with member variables
Actual Parameter: The variable int sum; return 1; name, age, bs, da, hra and tsalary. PASS BY REFERENCE
or expression corresponding to a sum= a + b; else Total Salary is calculated by the In C programming, it is also
formal parameter that appears in printf("Sum=%d",sum); } return n*fact(n-1); } equation tsalary= (1+da+hra)* bs. possible to pass addresses as
the function call in the calling Functions with no arguments void main() { Read the values of an employee arguments to functions. To
environment. In the above and return one value int n; and display it. accept these addresses in the
example, x, y and z in the main // function to read two numbers printf("Enter the number:"); #include<stdio.h> function definition, we can use
function are the actual parameter and return its sum scanf("%d",&n); struct Employee{ pointers. In this method, the
of addvfunction. Formal parameter int add() { printf("Factorial=%d",fact(n)); } char name[30]; address of the actual parameters is
of add function are a, b and c int a,b,sum; Recursive program to print sum of int age; passed to formal parameters. So
printf("Enter the values of a & b"); digit of a number float bs; any change in formal parameters
PASS BY VALUE scanf("%d%d",&a,&b); #include<stdio.h> float da; will be reflected in the actual
In this parameter passing sum = a+b; int sod(int n) { float hra; parameters.
technique, a copy of actual return sum; } if(n<=0) float tsalary; }; Consider the program to swap two
parameter is passed to formal Functions with arguments and return 0; void main() { numbers using pass by reference
parameter. As a result, any changes one return value else struct Employee e; method
or modification happened to // function that takes two return n%10 + sod(n/10); } printf("Enter the name:"); #include<stdio.h>
formal parameter won’t reflect arguments and print their sum. void main() { scanf("%s",e.name); int swap(int *a,int *b) {
back to actual parameter. This can int add(int a,int b) { int n; printf("Enter the age:"); int temp=*a;
be explained with an example of return (a + b); } printf("Enter the number:"); scanf("%d",&e.age); *a= *b;
swapping program. Function that have multiple return scanf("%d",&n); printf("Enter the basic salary:"); *b=temp; }
#include<stdio.h> values printf("Sum=%d",sod(n)); } scanf("%f",&e.bs); void main() {
int swap(int a,int b) { #include <stdio.h> Recursive function to print printf("Enter the da:"); int x,y;
int temp; int even(num) { Fibonacci series scanf("%f",&e.da); printf("\nEnter the numbers:");
temp=a; if( num%2==0) #include<stdio.h> printf("Enter the hra:"); scanf("%d%d",&x,&y);
a= b; return 1; int fib(int n) { scanf("%f",&e.hra); printf("\nBefore swapping :
b=temp; } else if(n == 1) e.tsalary=(1+e.da+e.hra)*e.bs; x=%d\ty=%d\n",x,y);
void main() { return 0; } return 0; printf("Name=%s\n",e.name); swap(&x,&y);
int x,y; void main() { else if(n == 2) printf("Age=%d\n",e.age); printf("\nAfter swapping :
printf("Enter the numbers:"); int s,a; return 1; printf("Basic Salary=%.2f\n",e.bs); x=%d\ty=%d",x,y); }
scanf("%d%d",&x,&y); printf("enter a"); return fib(n-2)+fib(n-1); } printf("DA=%.2f\n",e.da);
printf("Before swapping : scanf("%d",&a); void main() { printf("HRA=%.2f\n",e.hra); FILE OPERATIONS
x=%d\ty=%d\n",x,y); printf("%d",even(a)); } int n,i; printf("Total 1) Opening a file
swap(x,y); Write a program to perform printf("Enter the limit:"); Salary=%.2f\n",e.tsalary); } A file must be “opened” before it
printf("After swapping : arithmetic operations using scanf("%d",&n); Program to create a structure can be used. Opening a file is
x=%d\ty=%d",x,y); } function for(i=1;i<=n;i++) Complex with member variables performed using the fopen()
Output #include<stdio.h> printf("%d\t",fib(i)); } real and img. Perform addition of function defined in the stdio.h
Enter the numbers:10 20 int add(int a,int b) { Program to print sum of digit of a two complex numbers using header file.
Before swapping: x=10 y=20 return (a+b); } number structure variables. The syntax for opening a file in
After swapping : x=10 y=20 int diff(int a,int b) { #include<stdio.h> #include<stdio.h> standard I/O is:
In above program we expect the return (a-b); } int sod(int n){ struct Complex { FILE *fp
program to swap the value of x and int mul(int a,int b) { if(n<=0) int real; fp = fopen("filename","mode");
y after calling the function swap return (a*b); } return 0; int img; }; – fp is declared as a pointer to the
with x and y as actual parameter. float div(int a,int b) { else void main() { data type FILE.(C has a special
But swapping does not take return (float)a/b; } return n%10 + sod(n/10); } struct Complex a,b,c; "data type" for handling
place as this uses call by value as int mod(int a,int b) { void main() { printf("Enter the real and img part files which is defined in the
parameter passing technique. return (a%b); } int n; of a:"); standard library 'stdio.h '.)
void main() { printf("Enter the number:"); scanf("%d%d",&a.real,&a.img); It is called the file pointer and has
Program to display prime numbers int x,y; scanf("%d",&n); printf("Enter the real and img part the syntax FILE*.
upto a range using function. printf("Enter the values:"); printf("Sum=%d",sod(n)); } of b:"); – filename is a string - specifies the
#include<stdio.h> scanf("%d%d",&x,&y); Program to pass a 2D matrix as scanf("%d%d",&b.real,&b.img); name of the file.
#include<math.h> printf("Sum=%d\n",add(x,y)); parameter and find its sum of all c.real = a.real + b.real; – fopen returns a pointer to the file
int checkPrime(int n) { printf("Difference=%d\n",diff(x,y)); the elements. c.img = a.img + b.img; which is used in all subsequent file
int flag=0,i; printf("Multiply=%d\n",mul(x,y)); #include<stdio.h> printf("c = %d + operations
for(i=2;i<=sqrt(n);i++) { printf("Division=%f\n",div(x,y)); int sum(int A[][30],int m,int n) { %di\n",c.real,c.img); } 2. Closing a file
if(n%i == 0) { printf("Modulo=%d\n",mod(x,y)); } int i,j,sum =0; The file (both text and binary)
flag =1; Function to sort an array. for(i=0;i<m;i++) { should be closed after
break; } } #include<stdio.h> for(j=0;j<n;j++) { reading/writing. Closing a file
if(flag == 0) int sort(int A[],int n) { sum = sum + A[i][j]; } } is performed using the fclose()
return 1; int i,j,temp; printf("\nSum=%d",sum); } function.
else for(i=0;i<n-1;i++) { void main() { fclose(fp);
return 0; } for(j=0;j<n-i-1;j++) { int A[30][30]; Here, fp is a file pointer associated
void main() { if(A[j]>A[j+1]) { int i,n,m,j; with the file to be closed.
int n,i; temp = A[j]; printf("Enter the order of matrix:"); – fclose() function closes the file
printf("Enter the range:"); A[j] = A[j+1]; scanf("%d%d",&m,&n); and returns zero on success, or EOF
scanf("%d",&n); A[j+1]= temp; } } } } for(i=0;i<m;i++) { if there is an error in closing the
for(i=2;i<=n;i++) { void main() { for(j=0;j<n;j++) { file.
if(checkPrime(i) == 1) int A[30]; printf("Enter the element:"); – This EOF is a constant defined in
printf("%d\t",i); } } int i,n; scanf("%d",&A[i][j]); } } the header file stdio.h.
printf("Enter the limit:"); sum(A,m,n); } 3. Reading and writing to a file
scanf("%d",&n);
for(i=0;i<n;i++) {
printf("Enter the element:");
scanf("%d",&A[i]); }
sort(A,n);
printf("Sorted Array\n");
for(i=0;i<n;i++)
printf("%d\t",A[i]); }
POINTERS OPERATIONS ON POINTERS RANDOM ACCESS TO A FILE Program to copy the content of
The pointer in C language is a Address of a variable can be 1) rewind() one file to another.
variable which stores the address assigned to a pointer variable. The rewind() function sets the file #include<stdio.h>
of another variable. This variable One pointer variable can be pointer at the beginning of the void main() {
can be of type int, char, array, assigned to another pointer stream. It is useful if you have to FILE *f1,*f2;
function, or any other pointer. The variable provided both points to use stream many times. char ch;
size of the pointer depends on the the items of same datatype. Syntax: rewind(file pointer) f1 = fopen("test.txt","r");
architecture. However, in 32-bit A NULL value can be assigned to a 2) fseek() f2 = fopen("copy.txt","w");
architecture the size of a pointer is pointer variable. If you have many records inside a while(feof(f1) == 0) {
2 byte. An integer quantity can be added file and need to access a record at ch=fgetc(f1);
Consider the following example to to or subtracted from a pointer a specific position, you need to fputc(ch,f2); }
define a pointer which stores the variable. The result will be a loop through all the records before printf("Successfully Copied");
address of an integer variable. pointer. it , to get the record. This will fclose(f1);
int n = 10; When we increment a pointer, its waste a lot of memory and fclose(f2); }
int *p = &n; // Variable p of type value is increased by the length of operation time. An easier way to Program to merge the content of
pointer is pointing to the address of its data type. get to the required data can be two files.
the variable n of type integer One pointer variable can be achieved using fseek() #include<stdio.h>
Declaration of Pointer Variable subtracted from another pointer fseek(FILE * stream, long int offset, void main() {
The pointer in C language can be variable provided both points to int pos); FILE *f1,*f2,*f3;
declared using * (asterisk symbol). the elements of the same array. The first parameter stream is the char ch;
It is also known as indirection The result will be an integer value. pointer to the file. The second f1 = fopen("file1.txt","r");
operator used to dereference a Two pointer variables can be parameter is the position of the f2 = fopen("file2.txt","r");
pointer. compared provided both points to record to be found, and the third f3 = fopen("merge.txt","w");
datatype *ptrvar; the items of same datatype. parameter specifies the location while(feof(f1) == 0) {
where ptrvar is any identifier A pointer variable can be where the offset starts. ch=fgetc(f1);
int *a; //pointer to integer compared with NULL values. Different positions in fseek() fputc(ch,f3); }
char *c; //pointer to char Program to find the sum of two Position Meaning while(feof(f2) == 0) }
Initialization of Pointer Variable numbers using pointers SEEK_SET --Starts the offset from ch=fgetc(f2);
The process of assigning the #include<stdio.h> the beginning of the file. fputc(ch,f3); }
address of a variable to a pointer void main() { SEEK_END --Starts the offset from printf("Successfully Merged"); }
variable is known as initialization. int x,y,sum,*xp,*yp; the end of the file. Program to reverse each content
All uninitialized pointers have some printf("Enter value of x:"); SEEK_CUR --Starts the offset from of file to another.
garbage value so it should be scanf("%d",&x); the current location of the cursor in #include<stdio.h>
initialized. printf("Enter value of y:"); the file. #include<string.h>
Example scanf("%d",&y); 3) ftell() void main() {
int a; xp=&x; ftell() in C is used to find out the FILE *f1,*f2;
int *p; //declaration yp=&y; position of file pointer in the file char str[30],rev[30];
p=&a; //initialization sum=*xp+*yp; with respect to starting of the file. int i,j;
Accessing Data through Pointers printf(" Sum is %d \n",sum); } Syntax of ftell() is: f1 = fopen("test.txt","r");
A variable can be accessed through Program to read and display an ftell(FILE *pointer) f2 = fopen("new.txt","w");
its pointer using unary operator ’*’. array using pointer. while(feof(f1) == 0) {
Also known as indirection operator #include<stdio.h> Program to display the content of fscanf(f1,"%s",str);
or dereferencing operator. #include<malloc.h> a file. j=0;
Consider the following example: void main() { #include<stdio.h> for(i=strlen(str)-1;i>=0;i--) {
#include<stdio.h> int p[30],i,n; void main() { rev[j]=str[i];
void main() { printf("Enter the size of array:"); FILE *fp; j++; }
int n = 10; scanf("%d",&n); char ch; rev[j]='\0';
int *p; for(i=0;i<n;i++) { fp = fopen("test.txt","r"); fprintf(f2,"%s ",rev); }
p = &n; scanf("%d",p+i); } while(feof(fp) == 0) { fclose(f1);
printf("Address of n=%u\n",&n); printf("Array Content\n"); ch=fgetc(fp); fclose(f2); }
printf("Value of n=%d\n",n); for(i=0;i<n;i++) { printf("%c",ch); }
printf("Address of p=%u\n",&p); printf("%d\t",*(p+i)); } } fclose(fp); }
printf("Value of p=%u\n",p); Program to swap two variables Content of test.txt
printf("Value of *p=%d\n",*p); // using pointers Program to count number of
NULL Pointer include<stdio.h> vowels in a given file.
A pointer that is not assigned any void main() { #include<stdio.h>
value but NULL is known as the int x=10,y=20, temp,*a,*b; void main() {
NULL pointer. If you don't have any printf("\nBefore Swapping"); FILE *fp;
address to be specified in the printf("\nValue of x is %d",x); char ch;
pointer at the time of declaration, //output 10 int countV=0;
you can assign NULL value. It will printf("\nValue of y is %d ",y); fp = fopen("test.txt","r");
provide a better approach. //output 20 while(feof(fp) == 0) {
int *p=NULL; a=&x; ch=fgetc(fp);
b=&y; if(ch == 'a' || ch == 'A' || ch=='e'
temp= *a; ||ch=='E' || ch == 'I' || ch == 'i'
*a= *b; ||ch == 'O' ||
*b=temp; ch=='o' || ch == 'U' ||ch == 'u') {
printf("\nAfter swapping"); countV++; } }
printf("\nValue of x is %d \n",x); printf("Count of
//output 20 Vowels=%d",countV);
printf("\nValue of y is %d \n",y); fclose(fp); }
//output 10

You might also like