programming in c

14
Programming in C December – 2011 Solved by – Satadru Banerjee 1) i) A declaration provides basic attributes of a symbol: its type and its name. A definition provides all of the details of that symbol--if it's a function, what it does; if it's a class, what fields and methods it has; if it's a variable, where that variable is stored. Often, the compiler only needs to have a declaration for something in order to compile a file into an object file, expecting that the linker can find the definition from another file. If no source file ever defines a symbol, but it is declared, errors at link time complaining about undefined symbols will be seen. ii) When programming, we store the variables in our computer's memory, but the computer has to know what kind of data we want to store in them, since it is not going to occupy the same amount of memory to store a simple number than to store a single letter or a large number, and they are not going to be interpreted the same way. That’s why different data types are used to declare different variables like float is used to store floating point values, int is used to store integer values etc. iii) For integer data types, there are three sizes: int, and two additional sizes called long and short, which are declared as long int and short int. The long is intended to provide a larger size of integer, and short is intended to provide a smaller size of integer. However, not all implementations provide distinct sizes for them. The requirement is that short and int must be at least 16 bits, long must be at least 32 bits, and that short is no longer than int, which is no longer than long. Typically, short is 16 bits, long is 32 bits, and int is either 16 or 32 bits. So all signed integers are limited to a specific limit to store data but unsigned integers can be of all sizes, int, long, and short. And that’s why for different memory requirements we need both the signed and unsigned integer. iv) A type conversion is a conversion between types. For example; int main() { char x; int i; x = 'a'; i = x; /* implicitly convert x to int, and assign the result to i */ } A cast is used to make the conversion explicit. So the above could be done using a cast. For Example: int main() { char x; int i; x = 'a'; i = (int)x; /* Explicitly convert x to int, assign the result to i */ } In some cases, a conversion is technically possible but disallowed under the rules of the language.

Upload: independent

Post on 01-Feb-2023

0 views

Category:

Documents


0 download

TRANSCRIPT

Programming in C December – 2011 Solved by – Satadru Banerjee

1) i) A declaration provides basic attributes of a symbol: its type and its name. A definition

provides all of the details of that symbol--if it's a function, what it does; if it's a class, what fields

and methods it has; if it's a variable, where that variable is stored. Often, the compiler only needs

to have a declaration for something in order to compile a file into an object file, expecting that the

linker can find the definition from another file. If no source file ever defines a symbol, but it is

declared, errors at link time complaining about undefined symbols will be seen.

ii) When programming, we store the variables in our computer's memory, but the computer has

to know what kind of data we want to store in them, since it is not going to occupy the same

amount of memory to store a simple number than to store a single letter or a large number, and

they are not going to be interpreted the same way. That’s why different data types are used to

declare different variables like float is used to store floating point values, int is used to store

integer values etc.

iii) For integer data types, there are three sizes: int, and two additional sizes called long and

short, which are declared as long int and short int. The long is intended to provide a larger size of

integer, and short is intended to provide a smaller size of integer. However, not all

implementations provide distinct sizes for them. The requirement is that short and int must be at

least 16 bits, long must be at least 32 bits, and that short is no longer than int, which is no longer

than long. Typically, short is 16 bits, long is 32 bits, and int is either 16 or 32 bits. So all signed

integers are limited to a specific limit to store data but unsigned integers can be of all sizes, int,

long, and short. And that’s why for different memory requirements we need both the signed and

unsigned integer.

iv) A type conversion is a conversion between types. For example;

int main(){ char x; int i; x = 'a'; i = x; /* implicitly convert x to int, and assign the result to i */}

A cast is used to make the conversion explicit. So the above could be done using a cast. For Example:

int main(){ char x; int i; x = 'a'; i = (int)x; /* Explicitly convert x to int, assign the result to i */}In some cases, a conversion is technically possible but disallowed under the rules of the language.

v)

No. Traditional If – Else Construct No. Ternary Operator

1.

2.

3.

Can be applied to more situations (such as function calls)It cannot shorten the volume of the program as there is no way to bypass writing the same lines or variables over and over.Example –if (a > 0) answer = compute(a, b, c, d, e);else answer = compute(-a, b, c, d, e);Longer than Ternary Operator when dealing with direct value comparisons or assignments.

1.

2.

3.

Its application is limited only to very few conditional checking.It is useful when a lot of duplicate codes are to be used otherwise.

Example –answer = compute(a > 0 ? a : -a, b, c, d, e);

Shorter and more concise when dealing with direct value comparisons and assignments.

vi) In C programming if two things are to be put in a condition of "For Loop" where only a single expression is expected the comma operator is used to render both the two specifically in the first and third controlling expressions.

Example: #include <stdio.h>main(){ int i, j; for (i = 0, j = 10; i < 3 && j > 8; i++, j--){ printf (" the value of i and j %d %d\n",i, j); }}

vii) Floating point values are not random in their behavior. Many results get rounded due to not having enough precision to represent the actual result (due to needing infinitely many places for the correct value) when they are tried to be compared. That's why we shouldn’t use floating point for equality comparisons.

viii) The switch and case keywords evaluate expression and execute any statement associated with constant-expression whose value matches the initial expression.If there is no match with a constant expression, the statement associated with the default keyword is executed. If the default keyword is not used, control passes to the statement following the switch block. Thus default keyword is very much usefully used to state all the other situations except the limited situations declared by the switch and case keywords.

x) #include<stdio.h> main() { if(printf("Hello World")) { } }ix) Similarity:

No. While Loop No. Do – While Loop

1.2.

It is a conditional operator.Increment is not a part of the condition of the loop. The initialization of variable can be done before loop and increment should be done inside the loop.

1.2.

It is a conditional operatorIncrement is not any part of the condition of the loop. The initialization of variable can be done before loop and increment should be done inside the loop.

Difference:

No. While Loop No. Do – While Loop

1.

2.

3.

Here the condition is tested first and then the statements are executed if the condition turns out to be true.

While loop do not run in case the condition given is false.

While loop is entry control loop.

1.

2.

3.

Here the statements are executed for the first time and then the conditions are tested, if the condition turns out to be true then the statements are executed again.A do while loop runs at least onceeven though the condition given is false.

Do while is exit control loop.

xi) #include<stdio.h>main(){

int a,b; printf("Enter the two values\n\n"); scanf("%d%d",&a,&b); printf("\nValue of a = %d \n Value of b is = %d \n\n",a,b); printf("Press any key to Swap the values...\n\n"); getch(); a=a*b; b=a/b; a=a/b; printf("After swapping : \n Value of a = %d \n Value of b = %d",a,b); getch();

}

xii) A pointer in c which has not been initialized, neither refers to a legitimate object, nor is NULL is known as wild pointer.

Example:void main(){int *ptr;printf("%u ",ptr);printf("%d",*ptr);}

xiii) A function prototype is a declaration of a function that omits the function body but does specify the function's return type, name, arity (the number of arguments that a function can take)and argument types. While a function definition specifies what a function does, a function prototype can be thought of as specifying its interface. In a prototype, argument names are optional; however, the type is necessary along with all modifiers.

Example: int fac(int n); /* This prototype specifies that in this program, there is a function named "fac" which takes a single integer argument "n" and returns an integer. */

xiv) Preprocessor directives are commands that are interpreted by the compiler and affect the output or behavior of the build process. These are typically used to make source programs easy to change and easy to compile in different execution environments. Directives in the source file tell the preprocessor to perform specific actions. For example, the preprocessor can replace tokens in the text, insert the contents of other files into the source file, or suppress compilation of part of the file by removing sections of text.

Examples: #include, #define, #import, etc.

xv) Array elements are stored in memory one after the other, in case of a one-dimensional array. The elements of the array are stored respectively in the successive memory locations. Higher array indices correspond to higher memory addresses.

With multi-dimensional arrays in C language the array is stored in ROW MAJOR ORDER. The elements must carry two dimensional numbers to indicate their position in the table so these array elements are stored in respectively in the successive memory location according to its row-column number.

B) i) #include<stdio.h>main(){int no, rem, n, flag=0;printf("\nEnter a Number: ");scanf("%d",&no);n=no;while(no>2){rem=no%2;if(rem==1){flag=1;break;}elseno=no/2;}if(flag==1)printf("\n%d is not a Power of two.",n);elseprintf("\n%d is a Power of two.",n);getch();}

ii) #include<stdio.h>int main(){int odnum , sum=0; odnum=1;do{sum=sum+odnum; odnum=odnum+2;

}while(odnum<=100);printf("The Sum of all the odd numbers between 1 to 100 is %d\n",sum);getch();}

iii) A function call is an expression that passes control and arguments (if any) to a function and has the form.

"expression ( expression-list <SUB>opt</SUB> )"

where expression is a function name or evaluates to a function address and expression-list is a list of expressions (separated by commas). The values of these latter expressions are the arguments passed to the function. If the function does not return a value, then you declare it to be a function that returns void.If a declaration exists before the function call, but no information is given concerning the parameters, any undeclared arguments simply undergo the usual arithmetic conversions.

iv) The goto statement is a jump statement which jumps from one point to another point within a function. The goto statement is marked by label statement. Label statement can be used anywhere in the function above or below the goto statement.

Example: int n = 0; loop: ;

printf("\n%d", n); n++;

if (n<10) { goto loop; }

Syntax :goto [some function];

goto loop; goto operation;

v) The C do-while loop statement consists of a block of code and a Boolean condition. First the code block is executed, and then the condition is evaluated. If the condition is true, the code block is executed again until the condition becomes false.Generically, do/while is good for any sort of loop construct where one must execute the loop at least once. It is possible to emulate this sort of looping through either a straight while or even a for loop, but often the result is a little less elegant.

Properties of Do-while loop:

a) Here the statements are executed for the first time and then the conditions are tested, if the condition turns out to be true then the statements are executed again.

b) A do while loop runs at least once even though the condition given is false.

c) Do while is exit control loop.

d) Increment is not any part of the condition of the loop. The initialization of variable can be done before loop and increment should be done inside the loop.

vi) Unitialized pointer may contain any value, so if you should use them, the results are unpredictable; NULL value on the other hands explicitly means that the pointer does not point anywhere. An uninitialized pointer is a pointer which points unknown memory location while null pointer is pointer which points a null value or base address of segment.

Example: int *p; //Uninitialized pointerint *q= (int *)0; //Null pointer#include<stdio.h>int *r=NULL; //Null pointer

#include<string.h>#include<stdio.h>void main(){char *p; //Uninitialized pointerchar *q=NULL; //Null pointer;strcpy(p,"cquestionbank");strcpy(q,"cquestionbank");clrscr();printf("%s %s",p,q);getch();}

Output of the above program will be - cquestionbank (null)

vii) Example in which comma is behaving as separator as well as operator in c.

void main(){

int x=5,y=10,z=15,val; val=sum(x,(y=0,z=0,y),z); clrscr(); printf("%d",val); getch();

}sum(int x,int y,int z){

return x+y+z;}

Output of the above program: 20

viii)

No. Global Variable No. Local Variable

1.

2.

3.

4.

5.

These variables can be accessed (ie known) by any function comprising the program. They are implemented by associating memory locations with variable names. They do not get recreated if the function is recalled.

It is not mandatory.

Global variables ARE initialized by the system when user defines them!

A global variable is not always defined inside a block.Example:int i=4; /* i is a global Variable */ main() { i++; }

1.

2.

3.

4.

5.

These variables only exist inside the specific function that creates them. They are unknown to other functions and to the main program. As such, they are normally implemented using a stack. Local variables cease to exist once the function that created them is completed. They are recreated each time a function is executed or called.Local variables must always be defined at the top of a block.When a local variable is defined - it is not initialized by the system, user must initialize it himself.A local variable is defined inside a block and is only visible from within the block.Example:main() { int i=4; /* i is a local Variable */ i++; }

ix) Inter Function Communication is of 3 kinds. i) Downward data flow. ii) Upward Data flow iii) Bidirectional Data flow. In all of the three the rules of using array is defined bellow -

If user declare a variable or array in one function it will be readily available within that function, but it will not be visible (available) to another function unless user "pass" it (or a pointer to it) to that function via an argument. This is the concept of "locally-scoped"

If user declares a variable or array globally (outside of all functions) it will be equally available to any function. Warning: "Globally-scoped" variables are very tempting, but are generally a bad idea -- for it creates multiple problems and errors -- and user should avoid using them.

2) a) #include<stdio.h>int main(){char s[]="man";int i;for(i=0;s[i];i++)printf("\n%c%c%c%c",s[i],*(s+i),*(i+s),i[s]);getch();}

Output of the above program will be :

mmmmaaaannnn

Explanation: Here the for loop is used to read the elements of the string and here by using s[i],*(s+i),*(i+s),i[s] the address of the each row of the array where the string is contained is defined by different ways. As all the definitions s[i],*(s+i),*(i+s),i[s] points to same address of the array block each of the letter of the word is printed 4 times.

b) #include<stdio.h>main(){ int n, reverse = 0, temp; printf("Enter a number to check if it is a palindrome or not\n");

scanf("%d",&n); temp = n; while( temp != 0 ) { reverse = reverse * 10; reverse = reverse + temp%10; temp = temp/10;

} if ( n == reverse )

printf("%d is a palindrome number.\n", n); else

printf("%d is not a palindrome number.\n", n); getch();}

3) a) #include <stdio.h>int main(){float me=1.1; double you=1.1; if(me==you)printf("I Love U");else

printf("I Hate U"); getch();}Output of this program will be – “I Hate You” [এই ��া�াম �থেকই �বাঝা যাে� ��কত� া ছা�েদর ব�াপাের কী

মেনাভাব �পাষণ কেরন]Explanation : Here the value of you is half of 1.1 which is 0.55 . It is not equal to value of me. So it printed that.

b) program to print equilateral hollow triangle -

#include <stdio.h>#define MAX_LINE_LEN 80char line[MAX_LINE_LEN];const char star = '*';const char space = ' ';

int main() { int n,m,i,j; n=5;

for (i = 0, m = n-1; i < n; i++, m--) { for (j = 0; j < m; j++) printf("%c",space);

for (j = 1; j < i+1; j++) {if(j==2 && i==3) printf("%c ",space); else

printf("%c ",star); }

printf("\n"); } getch();}

4) a) #include <stdio.h>int main(){

char*p;printf("%d%d",sizeof(*p),sizeof(p));getch();}

Output of the above program will be – 14

Explanation: The sizeof operator gives the amount of storage, in bytes, required to

store an object of the type of the operand. Usually the char value of “p” requires 4

bites storage space and on the other hand the char value of “*p” requires only 1 byte

of storage space. So it printed 14.

b) #include<stdio.h>

#include<conio.h>

#include<math.h>

int main()

{

int x,y;

long c;

printf("Enter the value to x and y\n");

scanf("%d%d",&x,&y);

c=pow(x,y); /* pow function written under math.h and it calculate the power */

printf("%d to the Power %d is = %ld",x,y,c);

getch();

}

5) a) #include<stdio.h>

int main()

{

int i=1;

while(i<=5)

{

printf("%d",i);

if(i>2)

goto here;

i++;

}

getch();

}

The above program will not compile and will show errors. As we used a label “here”

but we didn’t define it anywhere in the program so it will show up a Build Error.

b) #include<stdio.h>

#include<conio.h>

#include<string.h>

int main()

{

char s[100];

int b,c,d,e,i,l,p;

b=c=d=e=0;

printf("\n\t Enter the string :\n\n");

gets(s);

l=strlen(s);

for(i=0;s[i]!='\0';i++)

{

if((s[i]>=65&&s[i]<=90||s[i]>=97&&s[i]<=122))

b++;

if(s[i]>=48&&s[i]<=57)

c++;

if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'||s[i]=='A'||s[i]=='E'||s[i]=='I'||s[i]==

'O'||s[i]=='U')

d++;

if (s[i]==' ')

e++;

}

p=b-d;

printf("\n\t No of vowels=%d \n",d);

printf("\n\t No of consonants=%d \n ",p);

printf("\n\t No of digits=%d \n",c);

printf("\n\t no of words=%d \n ",e+1);

printf("\n\t No of specal character=%d \n",l-b-c-e);

getch();

}

6) a) int main()

{

int i=0;

for(;i++;);

printf("%d",i);

getch();

}

The output of the above program will be 1

Explanation: Here the value of i is initialized to 0 and after that a for loop is used

where it is commanded to increase the value of i +1 but no upper or lower limit is

defined in the loop. So the increment only worked once and the value of i is changed

to 1 from 0. So when the value of i is printed at the last of the program it only prints 1

as the value of i.

b) #include <stdio.h>

#define MAX 10

int read_intaray(int scores[], int lim);

void print_intaray(int scores[], int lim);

int main()

{ int n, exam_scores[MAX];

printf("List of the Numbers\n\n");

n=read_intaray(exam_scores, MAX);

print_intaray(exam_scores,n);

}

/* Function reads scores in an array. */

int read_intaray(int scores[], int lim)

{ int n, count=0;

printf("Type Numbers, EDF to quit\n");

while((count<lim) && (scanf("%d",&n)!=EDF))

{

scores[count] = n;

count++;

}

return count;

}

/* Function prints lim elements in the array scores. */

void print_intaray(int scores[] , int lim)

{ int i;

printf("Numbers\n\n");

for (i=0;i<lim;i++)

printf("%d\n",scores[i]) ;

}

7) a) Switch case is a command used to give a pre-determined solution for a selected condition. For instance, while doing some operation, user will be asked, Enter 1 to continue; Enter 2 to quit etc.So, such already solutions can be fed using Switch cases. It is helpful only when the options to choose are only integral values.

This kind of switch – case commands can be used when the list is a pre-conceived one and there's not any other choice left to choose, for example: List of items on a Menu card and so on. The basic format or situation for using switch case is outlined below. The value of the variable given into switch is compared to the value following each of the cases, and when one value matches the value of the variable, the computer continues executing the program from that point.

switch ( <variable> ) {case this-value: Code to execute if <variable> == this-value break;case that-value: Code to execute if <variable> == that-value break;...default: Code to execute if <variable> does not equal the value following any of the cases break;}

Limitation : This statement can't be used for non-integral values.

b) A union can be viewed as a variable type that can contain many different variables (like a structure), but only actually holds one of them at a time (not like a structure). This can save memory if a group of data is present where only one of the types is used at a time. The size of a union is equal to the size of its largest data member. In other words, the C compiler allocates just enough space for the largest member. This is because only one member can be used at a time, so the size of the largest, is the most user will need. Example:

union time{long simpleDate;double perciseDate;}mytime;

The union above could be used to either store the current time (in seconds) to hold time accurate to a second. Or it could be used to hold time accurate to a millisecond. Presumably there are times when user would want one or the other, but not both. This declaration should look familiar. It is the same as a struct definition, but with the keyword union instead of struct.

No. Structure No. Union

1.

2.

3.

4.

We can access all the members of structure at anytime.Memory is allocated for all variables.

All members of structure can be initialized.'struct' keyword is used to declare structure.

1.

2.

3.

4.

Only one member of union can be accessed at anytime.Allocates memory for variable which variable require more memory.Only the first member of a union can be initialized.'union' keyword is used to declare union.

8) a) There are following storage classes which can be used in a C Program

autoregisterstaticextern

auto - Storage Class

auto is the default storage class for all local variables. -Storage: Memory

-Default initial value: Garbage value-Scope: Local to the block in which defined-Life: till the control remains within the block in which defined.

{ 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.

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 can’thave the unary '&' operator applied to it (as it does not have a memory location). -Storage: CPU registers

-Default initial value: Garbage value-Scope: Local to the block in which defined-Life: till the control remains within the block in which defined

{ register int Miles;

}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 implementationrestrictions.

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. -Storage: Memory

-Default initial value: Zero-Scope: Local to the block in which defined-Life: value of variable persists between different function calls.

static int Count; int Road; { printf("%d\n", Road); }static variables can be 'seen' within all functions in this source file. At link time, the static variables defined here will not be seen by the object modules that are brought in.

extern - Storage Class

extern is used to give a reference of a global variable that is visible to ALL the program files. 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.

When you have multiple files and you define a global variable or function which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to declare a global variable or function in another file. -Storage: Memory

-Default initial value: Zero-Scope: global-Life: As long as program execution does not come to an end.

File 1: main.c int count=5; main() { write_extern(); }

File 2: write.c void write_extern(void); extern int count; void write_extern(void) { printf("count is %i\n", count); }

Here extern keyword is being used to declare count in another file.

b)

No. Pass By Reference No. Pass By Value:

1.

2.

3.

4.

In Pass by reference address of the variable is passed to a function. Whatever changes made to the formal parameter will affect to the actual parametersSame memory location is used for both variables.(Formal and Actual)

It is useful when you required to return more than 1 values

example : // Pass by Referencevoid Get( int &nIndex){ nIndex = 10;}void main(){ int x = 100; cout<<Get( x );}output: 10;

1.

2

3.

4.

In this method value of the variable is passed. Changes made to formal will not affect the actual parameters.

Different memory locations will be created for both variables.

Here there will be temporary variable created in the function stack which does not affect the original variable.

example : // Pass by Valuevoid Get( int nIndex){ nIndex = 10;}void main(){ int x = 999; cout<<Get( x );}output : 999

-------------------------------