SEM 1 BC0034 Computer Concepts C Programming

21
Suresh Kumar Suthar Roll No: 520776763 BCA 1 st Semester BC0034 – 01 COMPUTER CONCEPTS & C PROGRAMMING 1. Explain the various data types used in C with suitable examples. Ans: C language has a rich set of data types. Storage representations and machine instruction to handle constants differ from machine to machine. The variety of data types available allow the programmer to select the type appropriate to the needs of the application as well as the machine. C supports three classes of data types: 1. Primary or Fundamental data types: This includes char, int, float, and void data types. 2. Derived data types: This includes pointer and array. 3. User-defined data types: This includes structure and unions. Integer Types: Integers are whole numbers with a range of values supported by a particular machine. Integers occupy one word of storage, and since the word size of machines vary (16 or 32 bit) the size of the integer that can be stored depends on the computer. If we use a 16 bit word length, the size of the integer value is limited to the range - 32768 to +32767 (that is -2 15 to +2 15 -1). A signed integer uses one bit for sign and 15 bits for the magnitude of the number. Similarly, a 32 word length can store an integer ranging from -2,147,438,648 to +2,147,483,647. C has three classes of integer storage. Namely short int, int and long int. in both signed and unsigned forms. Suresh Kumar Suthar Roll No: 520776763 BC0034 – 01 COMPUTER CONCEPTS & C PROGRAMMING 1

Transcript of SEM 1 BC0034 Computer Concepts C Programming

Page 1: SEM 1 BC0034 Computer Concepts C Programming

Suresh Kumar SutharRoll No: 520776763BCA 1st Semester

BC0034 – 01

COMPUTER CONCEPTS & C PROGRAMMING

1. Explain the various data types used in C with suitable examples.

Ans: C language has a rich set of data types. Storage representations and machine instruction to handle constants differ from machine to machine. The variety of data types available allow the programmer to select the type appropriate to the needs of the application as well as the machine. C supports three classes of data types:1. Primary or Fundamental data types: This includes char, int, float, and void data types.2. Derived data types: This includes pointer and array.3. User-defined data types: This includes structure and unions.

Integer Types: Integers are whole numbers with a range of values supported by a particular machine. Integers occupy one word of storage, and since the word size of machines vary (16 or 32 bit) the size of the integer that can be stored depends on the computer. If we use a 16 bit word length, the size of the integer value is limited to the range -32768 to +32767 (that is -215 to +215 -1). A signed integer uses one bit for sign and 15 bits for the magnitude of the number. Similarly, a 32 word length can store an integer ranging from -2,147,438,648 to +2,147,483,647.C has three classes of integer storage. Namely short int, int and long int. in both signed and unsigned forms.

Character Types: A single character can be defined as character (char) type data. Characters are usually stored in 8 bits (one byte) of internal storage. The qualifier signed or unsigned may be explicitly applied to char. While unsigned chars have values between 0 and 255, signed char have values from -128 to +127.

Floating Point Types: Floating point or real number are stored in 32 bits (on all 16 bit and 32 bit machines), with 6 digits of precision. Floating point numbers are defined in C by the keyword float. When the accuracy provided by a float number is not sufficient, the type double cab be use to define the number. A double data type number uses 64 bits giving a precision of 14 digits. These are known as double precision numbers.

Suresh Kumar Suthar Roll No: 520776763 BC0034 – 01 COMPUTER CONCEPTS & C PROGRAMMING

1

Page 2: SEM 1 BC0034 Computer Concepts C Programming

Void Types: The void types has no values. This is usually used to specify the type of functions. The type of a function is said to be void when it does not return any value to the calling function. It also play the role of a generic type, meaning that it can any of the other standard type.

Following tables shows the Size and Range of Data Types on a 16-bit Machine:

Type Size (bits/bytes) Rangechar or signed char 8 / 1 -128 to 127unsigned char 8 / 1 0 to 255int or signed int 16 / 2 -32,768 to +32,767unsigned int 16 / 2 0 to 65,535short int orunsigned short int 8 / 1 -128 to 127signed short int 8 / 1 0 to 255long int or -2,147,483,648 tosigned long int 32 / 4 +2,147,483,647unsigned long int 32 / 4 0 to 4,294,967,295float 64 / 8 3.4E - 38 to 3.4E + 38double 64 / 8 1.7E-308 to 1.7E+308long double 80 / 10 3.4E-4932 to 1.1E-4932

Suresh Kumar Suthar Roll No: 520776763 BC0034 – 01 COMPUTER CONCEPTS & C PROGRAMMING

2

Page 3: SEM 1 BC0034 Computer Concepts C Programming

2. Discuss the different types of operators used in C with an example for each.

Ans: C supports a rich set of operators. They are classified into following categories:1. Arithmetic operators2. Relational operators3. Logical operators4. Assignment operators5. Increment and decrement operators6. Conditional operators7. Bitwise operators8. Special operators(Comma ‘,’ and sizeof() operator)

Arithmetic operators: C provides all the basic arithmetic operators which are following:

Operator Description Example

+ Addition or unary plus 5+4 Result 9

-Subtraction or unary minus

5-4 Result 1

* Multiplication 5*4 Result 20

/ Division 5/4 Result 1

% Modulo division 5/4 Result 1

Relational operators:

C provides all the basic relation operators to compare two or more quantities and depending on their relation taking decision. These operators and their meanings are as below.

Operator Description Example

> greater than 5 > 4

>= greater than or equal to mark >= score

< less than height < 75

<= less than or equal to height <= input

== equal to score == mark

!= not equal to 5 != 4

Suresh Kumar Suthar Roll No: 520776763 BC0034 – 01 COMPUTER CONCEPTS & C PROGRAMMING

3

Page 4: SEM 1 BC0034 Computer Concepts C Programming

Logical operators:

In addition to the relational operators, C has the following three logical operators. The logical operators && and || are used when we want to test more than one condition and make decision.

Operator Description Example

&& Logical AND If(1< i && I <10) ...

|| Logical OR If (i <5 || I =5) ...

! Logical NOT If ( i !=5) ...

Assignment operators:

Assignment operators are used to assign the result of an expression to a variable.

Operator Description Example

= Assignment Operator a= 5

Increment and decrement operators(Or Binary Operator):

C provides shortcuts to add or subtract constant 1 to a variable.

Operator Description Example

++ Increment a=a++

-- Decrement a=a--

Conditional operators:

The conditional operator (ternary operator) pair “?:” is available in C to construct conditional expressions of the form

Expr1?expr2:expr3For examplea=100;b=200;c=(a>b)?a:b;Result: c=200This is same as if..else statement as follows:

Suresh Kumar Suthar Roll No: 520776763 BC0034 – 01 COMPUTER CONCEPTS & C PROGRAMMING

4

Page 5: SEM 1 BC0034 Computer Concepts C Programming

if (a>b)c=a;

elsec=b;

Bitwise operators:

The bitwise operators operate on integers thought of as binary numbers or strings of bits. These operators let us work with the individual bits of a variable; one common use is to treat an integer as a set of single-bit flags.

Operator Description Example

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

<< Shift left

>> Shift right

Special operators:

C supports some special operators like ‘,’ and sizeof() operators.The ‘,’ (comma) operator can be used to link the related expression together.The sizeof() is a compile time operator and, when used with an operand it returns the numbers of bytes the operand occupies. The operand may be variable, a constant or a data type qualifier.

Operator Description Example

, Comma OperatorValue=(x=10, y=5, x+y) Results: value=15

sizeof() Sizeof() Operator k= sizeof(235L)

Suresh Kumar Suthar Roll No: 520776763 BC0034 – 01 COMPUTER CONCEPTS & C PROGRAMMING

5

Page 6: SEM 1 BC0034 Computer Concepts C Programming

3. Explain the different types of input and output statements used in C.

Ans:C support many input and output statements. It also supports formatted input and output.Basic Character Input & Output:

getchar() function: It reads one character from the standard input. If there is no more characters available, the special value EOF will be return.Example: char c;

….c=getchar();

putchar() function: It writes one character to the standard output (Monitor).Example: char c;

c=”A”;putchar(c);

Formatted Input:

Input data can be entered into the computer from a standard input device by means of the standard C library function scanf(). This function can be used to enter any combination of numerical values, single character and strings. The function returns the number of data items that have been entered successfully.Syntax: scanf( control string, arg1, arg2,….argn)The control string consist of control characters, whitespace characters and nor-whitespace characters. The control characters are preceded by a % sign and are listed below.

Control Character Explanation

%c A single character

%d A decimal integer

%i An integer

%e, %f, %g A floating-point number

%o An octal number

%s A string

%x A hexadecimal number

%p A pointer

%nAn integer equal to the number of characters read so far

%u An unsigned integer

Suresh Kumar Suthar Roll No: 520776763 BC0034 – 01 COMPUTER CONCEPTS & C PROGRAMMING

6

Page 7: SEM 1 BC0034 Computer Concepts C Programming

%[] A set of characters

%% A percent sign

Example: int i;float f;char c;char str[10];scanf(“%d %f %c %s”,&I,&f,&c,str);

Formatted Output:

Output data can be written from the computer onto a standard output device using the library function printf(). This function can be used to output any combination of numerical values, single characters and strings. It similar to the input function scanf(), except that its purpose is to display data rather than enter into the computer.Syntax: printf(control string, arg1, arg2, ….argn)The control string characters are listed above (same as input control string)Example: printf(“%d %o %x\n”, 100,100,100);

Will print : 100 144 64Printf(“%c %d %f %e %s %d%%\n”,’3’,4,3.24,66000000,”nine”,8);

Will print : 3 4 3.240000 6.600000e+7 nine 8%

Suresh Kumar Suthar Roll No: 520776763 BC0034 – 01 COMPUTER CONCEPTS & C PROGRAMMING

7

Page 8: SEM 1 BC0034 Computer Concepts C Programming

4. Define looping. Discuss the types of looping structures used in C with examples.Ans: Looping:

The loop or iteration construct, directs a program perform a set of operation again and again until a specified condition is achieved.This condition causes the termination of the loop.C contains three statements for looping:

While Loop: While loop construct contains the condition first. If the condition is satisfied the control executes the statement following the while loop exile, it ignores these statements.Syntax: while(condition)

{ statement1Statement2

}Example: : #include<stdio.h>

#include<conio.h>void main()

{int x;X=1;while(x<10){

printf(“x is %d /n”, x);x++;

}}

Do While Loop: Do while loop ensure that the program execute at least once and checks whether the condition at the end of the do-while loop is true or false.As long as the test condition is true the statement will be repeated. The control will come out from the loop only when the test condition is false.Syntax: do

{Statement1

Statement1}while(condition)

Example: : #include<stdio.h>

Suresh Kumar Suthar Roll No: 520776763 BC0034 – 01 COMPUTER CONCEPTS & C PROGRAMMING

8

Page 9: SEM 1 BC0034 Computer Concepts C Programming

#include<conio.h> void main()

{int x;X=1;do{

printf(“x is %d /n”, x);x++;

} while(x<10)}

For loop construct is used to execute a set of statements for a given number of times. Thus, it is a shorthand method for executing statement in a loop.Syntax: for(initial condition; test condition; increment or decrement)

{ Statement1 Statement2

}

Example: #include<stdio.h>#include<conio.h>

void main(){

int counter;for(counter=20; counter<=1; counter--){

printf(“%d”, counter);}

}

Suresh Kumar Suthar Roll No: 520776763 BC0034 – 01 COMPUTER CONCEPTS & C PROGRAMMING

9

Page 10: SEM 1 BC0034 Computer Concepts C Programming

5. Define functions. Write the advantages and disadvantages of functions.

Ans: Definition of Function:

A function is a routine or a set of instruction or code that performs a specific task and can be processed independently.When the program passes control to a function the function perform that task and returns control to the instruction following the calling instruction. The most important reason to use the function is make program handling easier as only a small part of the program is dealt with at a time.A function is a “black box” that we’ve locked part of our program into. The idea behind a function is that it compartmentalizes part of the program, and in particular, that the code within the function has some useful properties.

Advantages of Functions:

i) The length of a source program can be reduced by using functions at appropriate places. This factor is particularly critical with microcomputers where memory space is limited.ii) It is easy to locate and isolate a faulty function for further investigations.iii) A function may be used by many other programs. This means that a C programmer can build on what others have already done, instead of starting all over again from scratch.iv) It facilitates top-down modular programming. In this programming style, the high level logic of the overall problem is solved first while the details of each lower-level function are addressed later.v) Its interface to the rest of the program is clean and narrow.

Disadvantages of Functions:

vi) While adding a user function can speed up code that is best written in C rather than a scripting language, it is not always the best choice for implementation: vii) It requires the programmer to be well versed in C, including pointers, function pointers, dynamic memory allocation, and debugging. Often the headaches C causes, especially for the neophyte, far outweigh any run-time savings. Bugs in the code might not manifest themselves until well after the C function ends, making debugging a nightmare. viii) There may not be any speed advantage. Vortex is pretty fast at most operations; for small functions it may be just as fast - and much easier - to write the function in Vortex. Since Vortex already has powerful data processing functions, and the ability to execute external programs, it may be

Suresh Kumar Suthar Roll No: 520776763 BC0034 – 01 COMPUTER CONCEPTS & C PROGRAMMING

10

Page 11: SEM 1 BC0034 Computer Concepts C Programming

faster to <EXEC> the C code in a separate program and parse it in Vortex, especially as a quick prototype. ix) It's less portable. A C function means a new Vortex executable must be made if the hardware platform changes. Other Vortex users won't have the custom function in their taxis executable.

Suresh Kumar Suthar Roll No: 520776763 BC0034 – 01 COMPUTER CONCEPTS & C PROGRAMMING

11

Page 12: SEM 1 BC0034 Computer Concepts C Programming

6. Write a note on storage classes with examples.

Ans:

The “storage class” of a variable determines whether the item has a “global” or “local” lifetime. C calls these two lifetimes “static” and “automatic.” An item with a global lifetime exists and has a value throughout the execution of the program. All functions have global lifetimes.

Automatic variables, or variables with local lifetimes, are allocated new storage each time execution control passes to the block in which they are defined. When execution returns, the variables no longer have meaningful values.

C provides the following storage-class specifiers:

Syntax

storage-class-specifier : autoregisterstaticexterntypedef

i) auto - storage class

auto is the default storage class for local variables.

{

int Count;

auto int Month;

}

The example above defines two variables with the same storage class. auto can only be used within functions, i.e. local variables.

ii) register - Storage Class

register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and cant have the unary '&' operator applied to it (as it does not have a memory location).

{ register int Miles;}

Suresh Kumar Suthar Roll No: 520776763 BC0034 – 01 COMPUTER CONCEPTS & C PROGRAMMING

12

Page 13: SEM 1 BC0034 Computer Concepts C Programming

Register should only be used for variables that require quick access - such as counters. It should also be noted that defining 'register' goes not mean that the variable will be stored in a register. It means that it might be stored in a register - depending on hardware and implementation restrictions.

iii) static - Storage Class

static is the default storage class for global variables. The two variables below (count and road) both have a static storage class.

static int Count; int Road;

iv) extern - storage Class

extern defines a global variable that is visible to ALL object modules. When you use 'extern' the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined.

Source 1 Source 2 ------------ -------- extern int count; int count=5; write() main() { { printf("count is %d\n", count); write(); } }

The placement of variable and function declarations within source files also affects storage class and visibility. Declarations outside all function definitions are said to appear at the “external level.” Declarations within function definitions appear at the “internal level.”

The exact meaning of each storage-class specifier depends on two factors:

Whether the declaration appears at the external or internal level Whether the item being declared is a variable or a function

Suresh Kumar Suthar Roll No: 520776763 BC0034 – 01 COMPUTER CONCEPTS & C PROGRAMMING

13

Page 14: SEM 1 BC0034 Computer Concepts C Programming

7. Distinguish between arrays and pointers with suitable examples.

Ans:

An array is a single, preallocated chunk of contiguous elements (all of the same type), fixed in size and location. A pointer is a reference to any data element (of a particular type) anywhere. A pointer must be assigned to point to space allocated elsewhere, but it can be reassigned (and the space, if derived from malloc, can be resized) at any time. A pointer can point to an array, and can simulate (along with malloc) a dynamically allocated array, but a pointer is a much more general data structure

Due to the so-called equivalence of arrays and pointers, arrays and pointers often seem interchangeable, and in particular a pointer to a block of memory assigned by malloc is frequently treated (and can be referenced using []) exactly as if it were a true array.

An array is actually a pointer to the 0th element of the array. Dereferencing the array name will give the 0th element. This gives us a range of equivalent notations for array access. In the following examples, arr is an array.

Array Access

Pointer Equivalent

arr[0] *arr

arr[2] *(arr +2)

arr[n] *(arr +n)

The array is treated as a constant in the function where it is declared. This means that we can modify the values in the array, but not the array itself, so statements like arr ++ are illegal, but arr[n] ++ is legal.

Since an array is like a pointer, we can pass an array to a function, and modify elements of that array without having to worry about referencing and de-referencing. Since the array is implemented as a hidden pointer, all the difficult stuff gets done automatically.

Suresh Kumar Suthar Roll No: 520776763 BC0034 – 01 COMPUTER CONCEPTS & C PROGRAMMING

14

Page 15: SEM 1 BC0034 Computer Concepts C Programming

A function which expects to be passed an array can declare that parameter in one of two ways.

8. Write your own function in C to implement string length and string concatenation without using built in functions.

Ans:

Function in C to implement string length:

/*function to find the string length*/int mystrlen(char str[]) /* int type function, it will accept an array of characters and return total number of characters */{

int i;for(i=0; str[i] !=’\0’; i++){ }

return i;}/*function ends here*/

Function in C to implement string concatenation:

/*function to concatenate two string*/mystrconcat(char str1[], char str2[]){

int i,j;i=j=0;

while(str1[i] !=’\0’){

i++;}while(str2[j] !=’\0’){str1[i]=str2[j];

j++;i++;

}str1[i]=’\0’;}/*function ends here*/

/*in main() function use these function*/

Suresh Kumar Suthar Roll No: 520776763 BC0034 – 01 COMPUTER CONCEPTS & C PROGRAMMING

15

Page 16: SEM 1 BC0034 Computer Concepts C Programming

#inclued<stdio.h>main(){char str1[30], str2[30];printf(“Enter the first string :”);gets(str1);printf(“\n Enter the second string :”);gets(str2);printf(“Length of first string is : %d and length of second string is : %d \n”, mystrlen(str1), mystrlen(str2));mystrconcat(str1,str2);printf(“After concatenation the first string is : %s\n”, str1);}/*End of main()*/

Suresh Kumar Suthar Roll No: 520776763 BC0034 – 01 COMPUTER CONCEPTS & C PROGRAMMING

16