Free Essay

Programming Final Assignmentv1.1

In:

Submitted By pratikgoswami90
Words 5415
Pages 22
Task 1

LO 1.1

All high-level programming languages support the concept of data types. A data type defines a set of values that a variable can store along with a set of operations. Data types are used to store various types of data which is managed by program. Data type attaches with variable to determine the number of bytes to be allocate to variable and valid operations which can be performed on that variable. Although C has several built-in data types, it is not a strongly typed language, as are Pascal and Ada. C supports various data types and here some common data type as character, integer and floating-point types.

C defines five foundational data types as defined below:

▪ character

▪ integer

▪ floating-point

▪ double floating-point

▪ valueless

These are declared as by char, int, float, double, and void, respectively. These types form the basis for some other types also. The extent and choice of these and data types may contrast amongst processor natures and compilers.

However, in all belongings an object of type char is 1 byte. C stores character type inside as an integer. Each character has 8 bits so, we can have 256 different characters values (0-255). Character set is used to map between an integer value and a character.

The size of an int is ordinarily the same as the word length of the implementation setting of the program. C has 3 classes of integer storage namely short int, int and long int. All of these data types have signed and unsigned forms. A short int requires half the space than normal integer values. Unsigned numbers are always positive and consume all the bits for the magnitude of the number. For most 16-bit programmes, such as DOS or Windows 3.1, an int is fixed at 16 bits. For most 32-bit programmes, such as Windows 95/98/NT/2000 with different versions, an int size is fixed 32 bits. However, we can’t make any expectations about the size of an integer if we want our programmes to be handy to the all major range of environments. It is significant to realize that C stipulates only the minimal range of each data type, not its size in bytes.

The exact format of floating-point values will depend upon how they are implemented. Variables of type char are generally used to hold values defined by the ASCII character set. Values outside that range may be handled differently by different compilers. The range of float and double will depend upon the method used to represent the floating-point numbers. Standard C specifies that the minimum range for a floating-point value is 1E–37 to 1E+37. The minimum number of digits of precision for each floating-point type is shown in Table.

The type void either explicitly declares a function as returning no value or creates generic pointers. Both of these uses are discussed in subsequent chapters.

All Data Types Defined by the C Standard

|Bits |Minimal |Range |
|Char |8 |–127 to 127 |
|unsigned char |8 |0 to 255 |
|signed char |8 |–127 to 127 |
|int |16 or 32 |–32,767 to 32,767 |
|unsigned int |16 or 32 |0 to 65,535 |
|signed int |16 or 32 |Same as int |
|short int |16 |–32,767 to 32,767 |
|unsigned short int |16 |0 to 65,535 |
|signed short int |16 |Same as short int |
|long int |32 |–2,147,483,647 to 2,147,483,647 |
|long long int |64 |–(263 –1) to 263 –1 (Added by C99) |
|signed long int |32 |Same as long int |
|unsigned long int |32 |0 to 4,294,967,295 |
|unsigned long long int |64 |264 –1 (Added by C99) |
|float |32 |1E–37 to 1E+37 with six digits of precision |
| | |1E–37 to 1E+37 with ten digits of precision |
|double |64 |1E–37 to 1E+37 with ten digits of precision |
| | | |
|long double |80 | |

Ans. 1.2

Simple input output programme with operator

/* Magic number program #1. */

#include

#include

int main (void)

{

int magic; /* magic number */

int guess; /* user's guess */

magic = rand(); /* generate the magic number */

printf("Guess the magic number: ");

scanf("%d", &guess);

if(guess == magic) printf("** Right **");

return 0;

}

Ans. 1.3

Here we need to write down coding for one programme in C language, programmes has to calculate the sum of the odd and even integer from 1 to 100.

# include

#include

void main()

{

int a=1;

int sum=0,sum1=0;

clrscr();

while (a=40 && subj2>=40 && subj3>=40 && subj4>=40)
{
Result=“Pass”
}
Else
{
Result=“Fail”
}

Here in above example I have define one code for make progress report. I have define in first expression if and then in bracket we can see I have defined four different condition and if all condition is true then the result will be otherwise it will execute else condition which contain result = “fail”. In this case && condition is very useful for us to run all four query at same time otherwise we need to write down “if and else” condition each subject which is very long process. If we use && then we can use all four different thing in one query.

In the programme of leap year where AND and OR operators work together. The logic is that the year is either divisible by both 100 and 4, OR its only divisible by 4 not by hundred.

If( year % 4 == 0 && (( year % 100 != 0) || (year % 400 == 0)))

{

printf(“It is a leap year”);

}

Else

{

printf(“It is not a leap year”);

}

To check all this this nested loop could be used but by using logical operators the code became shorter and easy to write and understand.

Ans. 1.3.2

What is Loop

'A loop' is a part of code of a program which is executed continually.
During looping a set of statements are executed until some conditions for termination of the loop is encountered. A program loop therefore consists of two segments one known as body of the loop and other is the control statement. The control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop.
A loop declaration and execution can be done in following ways. o Check condition to start a loop o Initialize loop with declaring a variable. o Executing statements inside loop. o Increment or decrement of value of a variable.
There are three basic types of loops which are:

• “for loop” • “while loop” • “do while loop”

While loop :

This is an entry controlled looping statement. It is used to repeat a block of statements until condition becomes true. WHILE loops are very simple.
Syntax:

while(condition)
{
statements; increment/decrement;
}
In above condition the given test condition is calculated and if the condition is true then the body of the loop is performed. After the implementation of the body, the test condition is again calculated and if it is true, the body is accomplished once again. This process of repeated execution of the body continues until the test condition finally becomes false and the control is transported out of the loop. On exit, the program remains with the statements directly after the body of the loop. The body of the loop may have one or more statements. The braces are needed only if the body contained two are more statements.

Example program for generating ‘N’ Natural numbers using while loop:
# include < stdio.h > void main()
{
int n, i=0; printf(“Enter the upper limit number”); scanf(“%d”, &n); while(I < = n)
{
printf(“\t%d”,I);
I++; increment I to the next natural number.
}
}
In the above coded programme the looping concept is used to generate ‘n’ natural numbers. Here ‘n’ and ‘I’ are declared as integer variables and ‘I’ is initialized to value zero. A message is given to the user to enter the natural number till where user wants to produce the numbers. The entered number is read by programme and stored by the scanf statement in the programme. The while loop then checks whether the value of ‘I’ is less than n i.e., the user putted number if it is true then the control enters the loop body and prints the value of ‘I’ using the printf statement and increases the value of ‘I’ to the next natural number this procedure repeats till the value of I develops equal to or greater than the number given by the user.

The Do while statement:

The do while loop is also a nice of loop, which is same as to the while loop in contrast to while loop, the do while loop tests at the bottom of the loop after performing the body of the loop. Since the body of the loop is performed first and then the loop condition is verifyed we can be secure that the body of the loop is performed at least once. DO..WHILE loops are useful for things that want to loop at least once.

The syntax of the do while loop is: do { statements; (increment/decrement);
}while(condition);

In above synatx the statement is performed, then expression is assessed. If the condition expression is true then the body is performed again and this process continues till the conditional expression becomes false. When the expression becomes false than the loop terminates.

To understand the helpfulness of the do while construct reflect the following problem. The user must be prompted to press Y or N. In reality the user can press any key other than y or n. IN such case the message must be shown again and the user should be allowed to enter one of the two keys, clearly this is a loop construct. Also it has to be performed at least once. The following program exemplifies the solution.

/* Program to illustrate the do while loop*/
#include < stdio.h > //include stdio.h file to your program void main() // start of your program
{
char inchar; // declaration of the character do // start of the do loop
{
printf(“Input Y or N”); //message for the user scanf(“%c”, &inchar); // read and store the character
}
while(inchar!=’y’ && inchar != ‘n’); //while loop ends if(inchar==’y’) // checks whther entered character is y printf(“you pressed u\n”); // message for the user else printf(“You pressed n\n”);
} //end of for loop

I have defined one example in above code to create programme which can perform example of do while loop. I have define. A message is given to the user to enter the value Y or N. The entered value will read by programme and stored by the scanf statement in the programme. The while loop then checks whether the value entered of ‘y’ or inchar has not equal to ‘n’ i.e., the user enterd value ‘y’ if it is true then the control enters the loop body and prints the message ‘Toy pressed Y’ using the printf statement. Otherwise it will display message you have enterd value is ‘N’.

Difference between ‘do while’ and ‘while loop’ is: A do..while loop is basically a reversed while loop. A while loop says "Loop while the condition is true, and execute this block of code", a do..while loop says "Execute this block of code, and loop while the condition is true".

Ans. 1.4

C has three files (also called streams)
•stdin, stdout and stderr, meaning standard input and standard output and standard error file. • Stdin is the input which usually arrives from the keyboard of a computer. • stdout is usually the screen. • stderr is the route by which all error messages pass: usually the screen. • These files are just handed over to the local operating system to deal with and it chooses what to do with them. • printf () & scanf () • getchar() & putchar() • gets () & puts ()

Use the standard library functions where possible. They are portable and usually optimized.
Some standard library functions might even get inline expanded (memcpy()), so there's probably no performance problem.
You should use stuff that's offered. E.g. strerror() will tell a lot about the origin of an error reported by the operating system. Not using it will leave the user and support group clueless.
Don't use gets() and the scanf() family for safety (buffer overflow crashes or program corruption) and security reasons (buffer overflow exploits). Use fgets() respectively fgets();strtok();atoi(); etc. instead.

ANSI Standard C

EMBOSS C should follow this C89 standard. The semantics of this are given in the second edition of K&R and also in Harbison and Steele's C: A Reference Manual.

This standard introduced:
a) Types of arguments are specified in the function definitions.
b) Addition of void's and enum's
c) Ability to pass structures to functions and have structures as return values.
'a' and 'b' are welcome additions. In EMBOSS, passing whole structures around is deprecated (we have our own way of dealing with structures and, even if we hadn't, passing structures around is wasteful of stack memory and rather slow).
Programming style is a set of rules or guidelines used when writing the Error! Bookmark not defined. for a computer program. It is often claimed that following a particular programming style will help programmers to read and understand source code conforming to the style, and help to avoid introducing errors.
The programming style used in a particular program may be derived from the Coding conventions of a company or other computing organization, as well as the preferences of the author of the code. Programming styles are often designed for a specific programming language. Style considered good in C source code may not be appropriate for BASIC source code, and so on.
Field impacted by the selection of a Code Style are: • Re-usability o Self documenting code o Internationalization o Maintainability o Portability • Optimization • Build process • Error avoidance • Security

Standardization is important
No matter which particular coding style you pick, once it is selected, it should be kept throughout the same project. Reading code that follows different styles can become very difficult. In the next sections we try to explain why some of the options are common practice without forcing you to adopt a specific style.

Whitespace and indentation
Spaces, tabs and newlines (line breaks) are called whitespace. Whitespace is required to separate adjacent words and numbers. Conventions followed when using whitespace to improve the readability of code is called an indentation style. Every block of code and every definition should follow a consistent indention style. This usually means everything within { and }. However, the same thing goes for one-line code blocks.

For example, a program could as well be written using as follows:

// Using an indentation size of 2

if ( a > 5 ) { b=a; a++; }

However, the same code could be made much more readable with proper indentation:

// Using an indentation size of 2

if ( a > 5 ) {

b = a;

a++;

}

Placement of braces

Compound statement are very important in C, they also are subject of different coding styles, that recommend different placements of opening and closing braces ({ and }). Some recommend putting the opening brace on the line with the statement, at the end (K&R). Others recommend putting these on a line by itself, but not indented (ANSI C++). GNU recommends putting braces on a line by itself, and indenting them half-way. It is recommend picking one brace-placement style and sticking with it.

Examples:

if (a > 5) {

// This is K&R style

}

Comments
Comments are portions of the code ignored by the compiler which allow the user to make simple notes in the relevant areas of the source code.

• Single-line comments (informally, C++ style), start with // and continue until the end of the line. If the last character in a comment line is a \ the comment will continue in the next line.

• Multi-line comments (informally, C style), start with /* and end with */.

Task 2

Ans. 2.1

Here I have created one programme, which will give result of factorial value for the item entered by user.

# include
#include
void fact(long int); void main()
{
long int n; printf("Enter a number: "); scanf("%ld", &n); fact(n); } void fact(long int x)
{
long int b = 1;
{
printf("Factorial of % ld is ",x); while(x>=1) { b=b*x; x - - ;
}
printf("%ld", b); getche(); }
}

Ans. 2.1.1

What is a Function?

Functions are used in “C” for the following details, Function definition, Types of functions, Functions with no arguments and no return values, Functions with arguments but no return values, Functions with arguments and return values, Return value data type of function and Void functions.

The basic viewpoint of function is divide and master by which complex tasks are sequentially divided into humbler and more manageable tasks which can be easily handled. A program can be divided into smaller subprograms that can be developed and tested successfully.
A function is a comprehensive and self-determining program which is used (or invoked) by the main program or other subprograms. A subprogram receives values called arguments from a calling in program, performs controls and returns the outcomes to the calling program.
There are many advantages in using functions in a program they are:
1. It simplifies top down linked programming. In this programming style, the high level logic of the overall problem is resolved first while the details of each lower level functions is addressed later.
2. It is easy to locate and separate a faulty function for further examination.
3. The length of the source program can be compact by using functions at suitable places. This factor is grave with microcomputers where memory space is restricted.
4. 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 preliminary over from scrape.
5. Programming teams does a large percentage of programming. If the program is separated into subprograms, each subprogram can be written by one or two team members of the team rather than having the whole team to work on the compound program
6. A program can be used to sidestep rewriting the same classification of code at two or more locations in a program. This is especially useful if the code complex is long or complicated.
C also provides support for use of library functions and use well-defined functions. The library functions are used to carry out a number of usually used operations or controls. The user-defined functions are written by the programmer to carry out various separate tasks.

Functions are used in “C” for the following reasons:

1. Many programs need that a specific function is recurring many times instead of writing the function code as many timers as it is necessary we can write it as a single function and access the same function again and again as many times as it is necessary.
2. We can ignore writing jobless program code of some orders again and again.
3. Programs with using functions are compressed & hassle free to understand.
4. Testing and correcting errors is easy because errors are localized and corrected.
5. We can realize the flow of program, and its code simply since the readability is improved while using the functions.
6. A single function printed in a program can also be used in other programs also.

Function definition:

[ data type] function name (argument list) argument declaration;
{
local variable declarations; statements; [return expression]
}

Example : mul(a,b) int a,b;
{
int y; y=a+b; return y;
}

When the value of y which is the addition of the values of a and b. the last two statements ie, y=a+b; can be combined as return(y) return(a+b);

Types of functions:

A function may fit to any one of the following categories:
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and return values.

Functions with no arguments and no return values:

Let us consider the following program
/* This Program to illustrate a function with no argument and no return values*/
#include
main()
{
staetemtn1(); starline(); statement2(); starline(); }
/*function to print a message*/ statement1() { printf(“\n Sample subprogram output”);
}
statement2()
{
printf(“\n Sample subprogram output two”);
}
starline()
{
int a; for (a=1;ab) printf(“Largest element=%d”,a); else printf(“Largest element=%d”,b);
}
In the above case study program we could make the calling function to read the data from the terminal and pass it on to the called function. But function does not return any value.

Functions with arguments and return values:

The function of the type Arguments with return values will send arguments from the calling function to the called function and assumes the outcome to be resumed back from the called function back to the calling function.
To assure a high degree of portability between programs a function should commonly be coded without involving any input output operations. For example different programs may need different productivity formats for displaying the results. These shortcomings can be overcome by handing over the result of a function to its calling function where the refunded value can be used as mandatory by the program. In the above type of function the following steps are accepted out:
1. The function call transfers the controls laterally with duplicates of the values of the actual arguments of the specific function where the formal arguments are creates and assigned memory space and are given the values of the actual arguments.
2. The called function is executed line by line in typical fashion until the return statement is encountered. The return value is passed back to the function call is called function.
3. The calling statement is executed generally and arrival value is thus assigned to the calling function.

Return value data type of function:

A C function precedes a value of type int as the default data type if there no any other type is definite clearly. For example if function does all the controls by using float values and if the return statement such as return (sum); returns only the integer part of the sum. This is since we have not specified any return type for the sum. There is the compulsion in some cases it is vital to accept float or character or double data type. To enable a calling function to accept a non-integer value from a called function we can do the two things:
1. The obvious type specified consistent to the data type mandatory must be declared in the function header. The general form of the function definition is

Type_specifier function_name(argument list)
Argument declaration;
{
function statement;
}
The type specified tells the compiler, the type of data the function is to return.
2. The called function must be acknowledged at the start of the body in the calling function, similar any other variable. This is to tell the calling function the type of data the function is really recurring. The program given below clarifies the transfer of a floating-point value between functions done in a several function program. main()
{
float x,y,add(); double sub(0; x=12.345; y=9.82; printf(“%f\n” add(x,y)); printf(“%lf\n”sub(x,y); } float add(a,b) float a,b;
{
return(a+b);
}
double sub(p,q) double p,q;
{
return(p-q);
}
We can notice that the functions too are acknowledged along with the variables. These statements clarify to the compiler that the return type of the function add is float and sub is double.
Ans. 2.2

What are variables

Variables in C are recollection locations that are given names and can be allocated values. We use variables to store data in memory for later use. There are 2 basic types of variables in C which are numeric and character.

Numeric variables

Numeric variables can either be integer values or they can be Real values. Integer values are whole numbers without a fraction part or number point in them. Real numbers can have a decimal point in them.

Character variables

Character variables are letters of the alphabet as well as all characters on the ASCII chart and even the numbers 0 - 9. Characters must continuously be put between single quotes. A number put between single quotes is not the same thing as a number without them.

What are constants

The modification between variables and constants is that variables can variation their value at any time but constants can never alteration their value. Constants can be useful for items such as Pi or the charge on an electron. Using constants can stop you from changing the value of an item by mistake.

Declaring variables

To declare a variable we first put the type of variable and then give the variable a name. The following is a table of the names of the types of variables as well as their ranges: (Vine, 2007)

[pic]

We can name a variable whatever we like as long as it covers only letters, numbers or underlines and does not start with a number. It is a worthy to keep your variable names less than 32 characters long to save time on typing them out and for compiler compatibility reasons. Variables must always be acknowledged at the top before any other commands are used. Now let's declare an integer variable titled a and a character variable called b. int main()
{
int a; char b; return 0;
}

You can pronounce more than one variable at the same time in the following way: int main()
{
int a,b,c; return 0;
}

To declare a constant all you have to do it put the word const in front of a standard variable declaration and make allocate a value to it. int main()
{
const float pi = 3.14; return 0;
}

Signed and unsigned variables

The variance between signed and unsigned variables is that signed variables can be either negative or positive but unsigned variables can only be positive. By using an unsigned variable we can increase the maximum positive range. When we declare a variable in the normal way it is robotically a retained variable. To declare an unsigned variable we just put the word unsigned before our variable declaration or signed for a signed variable while there is no reason to declare a variable as signed since they already are. int main()
{
unsigned int a; signed int b; return 0;
}

Using variables in calculations

To assign a value to a variable you use the equals sign. int main()
{
int a; char b; a = 3; b = 'H'; return 0;
}

There are a rare diverse operators that can be used when performing calculations which are listed in the following table:

[pic]

To perform a design we need to have a variable to put the reply into. You can also use both variables and normal numbers in controls. int main()
{
int a,b; a = 5; b = a + 3; a = a - 3; return 0;
}

Reading and printing variables

We can read a variable from the keyboard with the scanf command and print a variable with the printf command.
#include

int main()
{
int a; scanf("%d",&a); a = a * 2; printf("The answer is %d",a); return 0;
}

The %d is for reading or printing integer values and there are others as shown in the following table:
[pic]

LO2.3

Passing data effectively between modules.

Here to explain how to pass data between two modules, first off all I need to take one example, so we can understand very easily.

I have defined one simple programme as example for passing data.

Code:

int main() { int a,b; a=5; foo(a); printf("%d", a); }

void foo(int x) { x = 7; }
If we have any inkling, we will see that the foo(a); statement in the main function is in fact a function call to the foo funtion. The foo function for the time being helps us to understand parameter passing in C. “a” is the parameter in this function call, and it matches with the “x” which is found in the declaration of the foo function. There are only 2 obvious choices. It's either 5 or 7. Here now we are supposing that we don't know anything about parameter passing in C.
According to normal definitions, if it is pass by reference. That means “a” is going to be changed. Thus it will print out 7. If it is pass by value, that means that “a” is not passed over to foo, only the value of “a” is passed over to foo. Thus “a” doesn't change and it will print out 5.
C only passes parameters by value. That means, it pass given a function call, it passes values over to the other function. In short, there are 2 ways. One is making use of the return value of the function. So we can change the code above a little bit.

int main() { int a,b; a=5; a = foo(a); printf("%d", a); }

int foo(int x) { x = x + 2; return x; }

In the above code, “a” is allocated to the outcome of the function foo. That means, foo returns a value that is int its “x” and that value is given to “a”, so we can say this is a simple way to change the value of “a”. However, we can only assign variables one by one, so what if we want to change more than one variable in a function call?
The answer: We get C to simulate (SIMULATE!) pass-by-reference.
To read beyond this line, we must need to know and understand pointers. Please refers the notes or read the other FAQ on pointers for more on pointers. The following assumes that pointers are understood.

int main() { int a,b; a=5; b = 7; foo(&a, &b); printf("%d %d\n", a,b); }

void foo(int *x, int *y) { *x = 6; *y = 8; }
In above case what values are passed over from the function call to foo is is &a and &b, which are addresses of “a” and “b” respectively. Thus “x” covers the address of variable “a”. And “y” covers the address of variable “b”. Since *x is the deference operator, we can say that instead of referring to x, *x is referring to a, thus effectively assigning 6 to a and the same for *y=8. C is still passing by value, but now it is faking pass by reference. Because these pointers variables being passed in as arguments into foo helps foo to indirectly refer to “a” and “b” which are local variables in another function.
We have confirmed that C only pass parameters by value. It makes use of pointers to simulate pass by references. Now we talk over something which is humbler, how parameters are passed in C.
To simplify a function declaration looks like the ensuing ( < parameter_lists>) {

}

: any legal type in C or structure. examples are int, int *, char * : an identifier which gives the name of the function : a list of variables whose values are given by the function call.It is a list usually comprised of variable declarations seperated by commas.
A function looks like this in general: ( , ,.....);

It is basically a function name monitored by a series of expressions within the parenthesis. The number of expressions should be the same as the number of arguments with which the function was acknowledged. Simply put, if the function declaration parameter list, contains 10 items, then it should be called with 10 expressions.
Each expression in itself is either a variable name, or many variable names collected together by arithmetic operators or logical operators such as +, -. *. /, ||,&& ... so on and so forth. It can also be an assignment statement. That is, we can, if we want to call function foo, use foo(c=2): . That means that 2 is assigned to c, and the expression calculates to the value of c and then 2 is passed over to foo, so when we want to find out what values are actuality passed over in a function call, the value of this expression is Every expression in C evaluates to some value, for example, a+b evaluates to the numerical value of sum of a and b. int main() { int a, b, c;

a = 4; b = 6; c = 7; foo(a--; ++b; c--);

}

Multilipy Array

#include
#include
void main()
{
int a[9],b[9],c[9],x,y,z; printf("Enter Value of x\n");
for(x=0;x

Similar Documents