c Programming Easwari

30
C PROGRAMMING BASIC TYPES AND OPERATORS: 1. Where is a C program born? The basic control of a computer rests with its operating system. This is a layer of software which drives the hardware and provides users with a comfortable environment in which to work. An operating system has two main components which are of interest to users: a user interface (often a command language) and a filing system. The operating system is the route to all input and output, whether it is to a screen or to files on a disk. A programming language has to get at this input and output easily so that programs can send out and receive messages from the user and it has to be in contact with the operating system in order to do this, and C programming language does this. 2. What is C? C is what it is called as compiled language . It is a computer programming language that can be used to create lists of instructions for a computer to follow. Once a C program is written, it must run through a C compiler to turn the program into an executable that the computer can run. 3. What is a compiler?

Transcript of c Programming Easwari

Page 1: c Programming Easwari

C PROGRAMMING

BASIC TYPES AND OPERATORS:

1. Where is a C program born?

The basic control of a computer rests with its operating system. This is a layer of software which drives the hardware and provides users with a comfortable environment in which to work. An operating system has two main components which are of interest to users: a user interface (often a command language) and a filing system. The operating system is the route to all input and output, whether it is to a screen or to files on a disk. A programming language has to get at this input and output easily so that programs can send out and receive messages from the user and it has to be in contact with the operating system in order to do this, and C programming language does this.

2. What is C?

C is what it is called as compiled language. It is a computer programming language that can be used to create lists of instructions for a computer to follow. Once a C program is written, it must run through a C compiler to turn the program into an executable that the computer can run.

3. What is a compiler?

Compilers translate source code from a high level programming language to a lower level language.

4. What is a source code?

Source code is a text written in a computer programming language. Source code is primarily used as input to the process that produces an executable program.

5. What is a library?

 A library is simply a package of code that someone else has written to make your life easier. It has a set of functions that may be used by a program and declare special data types. C has a large number of standard libraries like stdio, including string, time and math libraries.

Page 2: c Programming Easwari

6. What is a variable?

One of the fundamental things we need to be able to do in our applications is temporarily store data. We do these using variables, which are containers that can hold various types of data and be manipulated in various ways.

We use variables to store all sorts of data, but we must first tell the compiler what we are going to store in it. Here are several of the most important variables that you should know about for now:

int – for storing integers (numbers with no decimal point) char – for storing a character float – for storing numbers with decimal points double – same as a float but double the accuracy

7. How to name, declare and initialize a variable?

The variable name can contain letters, digits and the underscore but the first letter has to be a letter or the underscore. 

To declare a variable we specify its name and kind of data type it can store. The variable declaration always ends with a semicolon.

A variable can be initialized when it is declared or it can be initialized at any point in a program before using it.

9. What are the Types of variables?

1. Local variable: Variables declared within the function.2. Global Variable: variables known throughout the program. They are

declared outside all function and conventionally just after include statements.

3. Parameter Variable: They are used for passing values between functions. Their main job is to automatically initialize depending upon the data processed

Page 3: c Programming Easwari

9. What are constants?

Constants are values that never change. The constant may be character constant, string constant, integer constant and floating point constant.

A char constant is written with single quotes (') like 'A' or 'z'. The char constant 'A' is really just a synonym for the ordinary integer value 65 which is the ASCII value for uppercase 'A'. There are special case char constants, such as '\t' for tab, for characters which is not convenient to type on a keyboard.

10. What is an Identifier?

An identifier is a name. It can be the name of a variable, function, a structure or union, a member of a struct, union, etc.

11. What are the rules to be followed while creating an identifier?

There are some rules that must be followed when creating an identifier. An identifier is a sequence of one or more characters. It must start with a non-digit character; it can use upper and lower case a-z characters or universal character codes or an underscore character (_). After the first character, digits 0-9 may also be used.

12. What is a type qualifier?

They are used to qualify types, modifying the properties of variables in certain ways. There are three types

The qualifier 'const' is most often used in modern programs, and probably best understood. The addition of a 'const' qualifier indicates that the (relevant part of the) program may not modify the variable.

The qualifier 'volatile' indicates to the compiler, that a variable may be modified outside the scope of the program.

The qualifier ‘Restrict’ is one of the newest features added to C. It is applicable only to pointers. A restrict pointer is the only mean by which the data pointed to that object can be accessed.

Page 4: c Programming Easwari

13. What is a storage class specifier?

Storage class specifier when applied to a variable tells the compiler how to store that variable. There are four storage class specifiers in C.

1. Extern2. Static

3. Register

4. Typedef

Extern: There are three general use of extern. Initially it was used to before functions to indicate the function has global scope, but now, all the functions are automatically put in global scope and this use is now virtually no existent.

Second use of extern is to declare that a global variable used in the file is from an external file.

The third use is the commonly used one and it enables the programmer to use a variable without defining by marking it as extern

Static: It’s a high utility word often used in programming.

When applied to global variables, its scope is limited to file only i.e. other files included in the program has no clue of its existence.

When applied to local variables, the variable is stored in global variable memory space and not on stack.

Register: This is a compiler dependant keyword. Using the register keyword, the program runs faster since a register variable is stored in CPU register instead of RAM.

Typedef: It is a controversial storage class specifier since it doesn`t allocate storage, neither defines or modifies the type of storage when applied to a variable. Still it is defined in standard C. This has two advantages.

It makes the code source portable since we use own name for code generated by compiler for a particular environment

Page 5: c Programming Easwari

It creates self documenting code, making the code easier to understand.

12. What is a data type?

Data types are used to store various types of data that is processed by program. C supports various data types such as character, integer and floating-point types

13. What is Character data type?

C stores character type internally as an integer. Each character has 8 bits so we can have 256 different characters values (0-255). Now, how did this 256 characters come?

Each character has 8 bits, and there are only 2 bytes i.e. 0 and 1

1 Byte = 8 bits or 2^82^8 = 256and that is split that from -128 ~ 127

Syntax: char <variable name>; likechar ch = ‘a’;

Page 6: c Programming Easwari

14. What is Integer Data Type?Integer data types are used to store numbers and characters.

Syntax: int <variable name>; likeint num1;short int num2;long int num3;

15. What is Floating-point Data Type?

The floating-point data types are used to represent floating-point numbers. Floating-point data types come in three sizes: float (single precision), double (double precision), and long double (extended precision).

 Syntax: float <variable name>; likefloat num1;double num2;long double num3;16. What is Void data type?

The void type has no values therefore we cannot declare it as variable as we did in case of integer and float. It does not return any value.

17. What is the function of an operator in C? C operators can do arithmetic, compare data, modify variables, combine relationship logically... etc.

Operators taking just one operand are called unary operators.

Operators requiring two operands are called binary operators.

Arithmetic operators:

C supports almost common arithmetic operators such as +,-,*, / and modulus operator %. The modulus operator (%) returns the remainder of integer division calculation.  The modulus operator cannot be applied to a double or float.

Page 7: c Programming Easwari

Assignment operator:

It is the single equals sign (=). It copies the value from its right hand side to the variable on its left hand side.

Bitwise operators:

The bitwise operators perform bitwise-AND (&), bitwise-exclusive-OR (^), and bitwise-inclusive-OR (|) operations. The bitwise operators are preferred in some contexts because bitwise operations are faster than (+) and (-) operations and significantly faster than (*) and (/) operations.

The operands of bitwise operators must have integral types, but their types can be different. The commonly used bitwise operators are,

~ Bitwise Negation (unary) – flip 0 to 1 and 1 to 0 throughout

& Bitwise And

| Bitwise Or

^ Bitwise Exclusive Or

>> Right Shift by right hand side (RHS) (divide by power of 2)

<< Left Shift by RHS (multiply by power of 2

Logical operators and Relational operators:

C logical operators are used to connect expressions and / or variables to form compound conditions. The logical operators are

Relational operators are used to calculate the relationship between variables, whereas the logical operators calculate the logic in these relationships. Some of the relational operators are,

Operator Meaning

&& logical AND

|| logical OR

! logical NOT

Page 8: c Programming Easwari

== Equal

!= Not Equal

> Greater Than

< Less Than

>= Greater or Equal

<= Less or Equal

Increment and decrement operators:

C provides two operators for incrementing and decrementing the value of

variables.

The increment operator ++ add 1 to its operand.

The decrement operator -- subtracts 1 from its operand

The C increment and decrement operators can be used either as prefix operator or postfix operators.Compile time operator: C only provides one compile time operator known as

sizeof. Sizeof returns the size of the object passed to it as parameters in

parenthesis.

Type conversion: when variables and constants of different types are mixed in a

single expression, they are all converted into same type.

Ternary operator: The conditional operator or the ternary operator (?:) returns one of two values depending on the value of a Boolean expression. The conditional operator is of the form

condition ? first_expression: second_expression;

Page 9: c Programming Easwari

18. What is the difference between Logical operators and bitwise operators?Logical operators such as !, &&, and || always yield a Boolean value --

either true or false.

Bitwise operators yield a string of bits stored in a built-in variable of

type char, unsigned char, int and so on.

19. How are comments useful to programmers?Comments help programmer explain the complex logic of the code to make it

easier to maintain and enhance. C provides two types of comments are block

comments and inline comments.

Block comments begin with /* and end with  */

Inline comments begin with // and end with your comment.

20. What are the types of statements in C?

1. Conditional Statement:  It’s also called a selection statement. This

statement depends on the condition. This decides the flow of statements

based on evaluation of the results of condition. if - else and switch

statements always come in conditional statements.

If else:  if statement will have some condition (true or false), that is given by

the program .If the if condition will not be true than it will read

the else statement and execute the else statement and go to the next line of the

program for execution.

Page 10: c Programming Easwari

SYNTAX:

    if (condition) statement;

                    else statement;

OR

               if (condition) {                expresion1;                 }                else  {                 expresion2;               }Switch Statement: It has a built in multiple - branch structure and work similar to if else ladder generally. The input value to the switch statement construct is a int or char variable. Note that no float or any other data is allowed. This input variable is compared against a group of integer constant

SYNTAX:

switch (input) { case constant1 :  statement1;  break;  case constant2 :  statement2;  break;..case default :  statement n+1;  break;

2. Iteration Statements - These are used to run particular block statements repeatedly or in other words form a loop. for, while and do-while statements come under this category.

For: It provides unmatched flexibility and power to the program.This is an entry controlled looping statement.

Page 11: c Programming Easwari

In this loop structure, more than one variable can be initialized. One of the most important features of this loop is that the three actions can be taken at a time like variable initialization, condition checking and increment/decrement.Syntax:For (initialisation; test-condition; incre/decre){

statements;}

While: This is also an entry controlled looping statement. It is used to repeat a block of statements until condition becomes true.

Syntax:While (condition){

statements;increment/decrement;

}Do-while loop: This is an exit controlled looping statement. Sometimes, there is need to execute a block of statements first then to check condition. At that time such type of a loop is used. In this, block of statements are executed first and then condition is checked.

Syntax:

do{

statements;(increment/decrement);

}while(condition);

3. Jump Statements: These are used to make the flow of your statements from one point to another. Break, continue, goto and return come under this statements.

Page 12: c Programming Easwari

goto Statement: Goto is used for jumping from one point to another point in your function. Jump points or way points for goto are marked by label statements. Label statement can be anywhere in the function above or below the goto statement.Syntax:goto label1;.label1 :.label2 :

goto label2;

Break Statement: Break statement when encountered within a loop immediately terminates the loop by passing condition check and execution transfer to the first statement after the loop. In case of switch it terminates the flow of control from one case to another.

Page 13: c Programming Easwari

Return : Return statement has a special property that it can return a value with it to the calling function if the function is declared non - void. 

Continue Statement: It is analogues to break statement. Unlike break which breaks the loop, continue statement forces the next execution of loop bypassing any code in between

.

21. What is a function in C?

Function is a block of source code which does one or some tasks with specified purpose.

22. What are the types of functions?

There are 2(two) types of functions as:1. Built in Functions2. User Defined Functions

1. Built in Functions:These functions are also called as 'library functions'. These functions are provided by system. These functions are stored in library files. e.g. scanf() printf() strcpy strlwr strcmp strlen strcat

Page 14: c Programming Easwari

2. User Defined Functions:The functions which are created by user for program are known as 'User defined functions.

23. How is a function call done?

Function Call by Passing Value:

When a function is called by passing value of variables then that function is known as 'function call by passing values.'

Function Call by Returning Value:

When a function returns value of variables, which may be a reference to the object, then that function is known as 'function call by returning values.'

Function Call by Passing and Returning Value:

When a function passes and returns value of variables then that function is known as 'function call by passing and returning values.'

24. What is the structure of a function?

Function headerThe general form of function header is:

1 return_type function_name(parameter_list)

Function bodyFunction body is the place you write your own source code. 

Return statementReturn statement returns a value to where it was called. A copy of return value

being return is made automatically

Page 15: c Programming Easwari

COMPLEX DATA TYPES:

1. What is an array and how do you declare it?

An array in C language is a collection of similar data-type, means an array can hold value of a particular data type for which it has been declared. 

We can declare an array by specifying its data type, name and the fixed number of

elements the array holds between square brackets immediately following the array

name.

The following illustrates how to declare an array:

data_type array_name[size];

2.How do you initialize and declare an array?

Initializing ArraysIt is like a variable, an array can be initialized. To initialize an array, you provide

initializing values which are enclosed within curly braces in the declaration and

placed following an equals sign after the array name.

Here is an example of initializing an array of integers.

int list[5] = {2,1,3,7,8};

Accessing Array ElementYou can access array elements via indexes like 

array_name[index].

Indexes of array starts from 0 not 1 so the highest elements of an array

isarray_name[size-1].

3.What are the types of array?

Page 16: c Programming Easwari

1. One / Single Dimensional Array2. Two Dimensional Array3. Multi dimensional array.

Single / One Dimensional Array:

The array which is used to represent and store data in a linear form is called as 'single or one dimensional array.'Syntax:

Type name [size]

Two Dimensional Arrays:

The array which is used to represent and store data in a tabular form is called as 'two dimensional array.' Such type of array specially used to represent data in a matrix form.The following syntax is used to represent two dimensional array.Syntax:

Type name [size1] [size2]

Size1 is the number of 1D arrays and size2 is the size of that 1D array.Multi dimensional Array:

C allows more than 2D array. The general syntax for declaring this array is

Type name [size1] [size2]….[sizeX];

3. Can an array be passed as a parameter?

In C entire array cannot be passed as a parameter. Only the base address of the pointer is passed as an argument.

4.What is a pointer, what are its features?

C pointer is a memory address. To access memory address of variable we have to use pointer. 

Page 17: c Programming Easwari

* Pointer variable should have prefix '*'.* Combination of data types is not allowed.* Pointers are more effective and useful in handling arrays.* It supports dynamic memory management.* It reduces complexity and length of a program.* It helps to improve execution speed that results in reducing program execution time.

5. What is a string?

A string is a collection of characters. Strings are always enlosed in double quotes as "string_constant".Strings are used in string handling operations such as, Counting the length of a string. Comparing two strings. Copying one string to another. Converting lower case string to upper case. Converting upper case string to lower case. Joining two strings. Reversing string.

6. How do you declare a string? The string can be declared as follows:Syntax:char string_nm[size];Example:char name[50];

7. Explain the String StructureWhen compiler assigns string to character array then it automatically supplies null character ('\0') at the end of string. Thus, size of string = original length of string + 1. An example would be,

char name[7];name = "TECHNO"

Page 18: c Programming Easwari

8. How do you Read Strings?To read a string, we can use scanf() function with format specifier %s.

char name[50];scanf("%s",name);

The above format allows accepting only strings, which does not have any blank space, tab, new line, forming feed, carriage return.

9. How do you Write Strings?To write a string, we can use printf() function with format specifier %s.

char name[50];scanf("%s",name);printf("%s",name);

10. Define a null terminated string

String is terminated by a special character which is called as null terminator or null parameter (/0).  In ASCII table, the null terminator has value 0.

11. What is a storage class?

Storage class defines the the scope and lifetime of a variable.

Functions of storage class:To determine the location of a variable where it is stored ?Set initial value of a variable or if not specified then setting it to default value.Defining scope of a variable.To determine the life of a variable.

Page 19: c Programming Easwari

12. What are the types of storage class?

Automatic Storage Class :

o Keyword : autoo Storage Location : Main memoryo Initial Value : Garbage Valueo Life : Control remains in a block where it is defined.o Scope : Local to the block in which variable is declared.Syntax :

auto [data_type] [variable_name];

Example :

auto int a;

Register Storage Class :

o Keyword : registero Storage Location : CPU Registero Initial Value : Garbageo Life : Local to the block in which variable is declared.o Scope : Local to the block.Syntax :

register [data_type] [variable_name];

Example :

register int a;

Static Storage Class :

o Keyword : statico Storage Location : Main memoryo Initial Value : Zero and can be initialize once only.o Life : depends on function calls and the whole application or program.

Page 20: c Programming Easwari

o Scope : Local to the block.Syntax:

static [data_type] [variable_name];

Example:

static int a;External Storage Class:

o Keyword : externo Storage Location : Main memoryo Initial Value : Zeroo Life : Until the program ends.o Scope : Global to the program.Syntax :

extern [data_type] [variable_name];

Example:

extern int a;

13. What is a structure?

Structure is user defined data type which is used to store heterogeneous data under unique name. Keyword 'struct' is used to declare structure.The variables which are declared inside the structure are called as 'members of structure'.Syntax:

struct structure_nm{

<data-type> element 1;<data-type> element 2;- - - - - - - - - - -- - - - - - - - - - -

Page 21: c Programming Easwari

<data-type> element n;}struct_var;

Example :

struct emp_info{

char emp_id[10];char nm[100];float sal;

}emp;

14.How do you access a structure member?

Structure members can be accessed using member operator '.' . It is also called as 'dot operator' or 'period operator'.Syntax:structure_var.member;

15. What is a Union?Union is user defined data type used to stored data under unique variable name at single memory location.Syntax:

union union_name{

<data-type> element 1;<data-type> element 2;<data-type> element 3;

}union_variable;Example:

union techno{

int comp_id;char nm;float sal;

Page 22: c Programming Easwari

}tch;

16. What is the difference between a union and a structure?

 The major difference between structure and union is 'storage.' In structures, each member has its own storage location, whereas all the members of union use the same location. Union contains many members of different types, it can handle only one member at a time.

17. What is dynamic memory allocation in C?

C provides y a powerful and flexible way to manage memory allocation at runtime. It is called dynamic memory allocation. Dynamic means you can specify the size of data at runtime. With dynamic memory allocation, you can allocate and free memory as needed.

18. How to get to know the size of the data?

can get the size of data by usingsizeof() function. The sizeof() function returns a size_t an unsigned constant integer.

19. How to allocate memory in C?

We use malloc() function to allocate memory. Here is the function interface:

void * malloc(size_t size);

20. What is the use of calloc( ) and realloc( )?

The calloc() function not only allocates memory like malloc() function but also

allocates memory for a group of objects which are specified by the first argument

num.

Page 23: c Programming Easwari

The realloc() function takes in the pointer to the original area of memory to extend

and how much the total size of memory should be.

21. How do you free memory? When you use malloc() function to allocate memory, you implicitly get the

memory from a dynamic memory pool which is known as heap. The heap is

limited so you have to deallocate or free the memory, you requested when you

don't use it in any more. C provides function free() to allow you to free memory.

Below is the function prototype:

void free(void *ptr);