Monthly Archives: August 2016


Write a macro to demonstrate #define, #if, #else preprocessor commands. 6m Jun 2010

Write a macro to demonstrate #define, #if, #else preprocessor commands. 6

 

 Code:

#include <stdio.h>
#define CHOICE 100
int my_int = 0;
#if (CHOICE == 100)
void set_my_int()
{ my_int = 35; }
#else
void set_my_int()
{
my_int = 27;
}
#endif
main ()
{
set_my_int();
clrscr();
printf(“%d\n”, my_int);
getch();
}

#include <stdio.h>
#define CHOICE 100
int my_int = 0;
#if (CHOICE == 100)
void set_my_int()
{ my_int = 35; }
#else
void set_my_int()
{
my_int = 27;
}
#endif
main ()
{
set_my_int();
clrscr();
printf("%d\n", my_int);
getch();
}

Screen Shots:

C_program_Preprocessor

C_program_Preprocessor_Out

What do you understand by a decision-control statement? Give an example of each. 8m Jun 2010

What do you understand by a decision-control statement? Give an example of each. 8

In a C program, a decision causes a one-time jump to a different part of the program, depending on the value of an expression. Decisions in C can be made in several ways. The most important is with the if…else statement, which chooses between two alternatives. This statement can be used without the else, as a simple if statement.

Another decision control statement, switch, creates branches for multiple alternative sections of code, depending on the value of a single variable.

 

The if Statement

It is used to execute an instruction or sequence/block of instructions only if a condition is fulfilled. In if statements, expression is evaluated first and then, depending on whether the value of the expression (relation or condition) is “true” or “false”, it transfers the control to a particular statement or a group of statements.

 

Write a program to award grades to students depending upon the criteria mentioned

below:

  • • Marks less than or equal to 50 are given “D” grade
  • • Marks above 50 but below 60 are given “C” grade
  • • Marks between 60 to 75 are given “B” grade
  • • Marks greater than 75 are given “A” grade.

/* Program to award grades */

#include <stdio.h>

main()

{

int result;

printf(“Enter the total marks of a student:\n”);

scanf(“%d”,&result);

if (result <= 50)

printf(“Grade D\n”);

else if (result <= 60)

printf(“Grade C\n”);

else if (result <= 75)

printf(“Grade B\n”);

else

printf(“Grade A\n”);

}

OUTPUT

Enter the total marks of a student:

80

Grade A

 

Different forms of implementation if-statement are:

  • • Simple if statement
  • If-else statement
  • Nested if-else statement
  • Else if statement

 

The Switch Statement

Its objective is to check several possible constant values for an expression, something similar to what we had studied in the earlier sections, with the linking of several if and else if statements. When the actions to be taken depending on the value of control variable, are large in number, then the use of control structure Nested if…else makes the program complex.

 

Write a program that performs the following, depending upon the choice selected by the user.

  1.  calculate the square of number if choice is 1
  2.  calculate the cube of number if choice is 2 and 4
  3.  calculate the cube of the given number if choice is 3
  4.  otherwise print the number as it is

 

main()

{

int choice,n;

printf(“\n Enter any number:\n “);

scanf(“%d”,&n);

printf(“Choice is as follows:\n\n”);

printf(“1. To find square of the number\n”);

printf(“2. To find square-root of the number\n”);

printf(“3. To find cube of a number\n”);

printf(“4. To find the square-root of the number\n\n”);

printf(“Enter your choice:\n”);

scanf(“%d”,&choice);

switch (choice)

{

case 1 : printf(“The square of the number is %d\n”,n*n);

break;

case 2 :

case 4 : printf(“The square-root of the given number is %f”,sqrt(n));

break;

case 3: printf(“ The cube of the given number is %d”,n*n*n);

default : printf(“The number you had given is %d”,n);

break;

}

}

OUTPUT

Enter any number:

4

Choice is as follows:

1. To find square of the number

2. To find square-root of the number\n”);

3. To find cube of a number

4. To find the square-root of the number

Enter your choice:

2

The square-root of the given number is 2

Explain the difference between a top-down approach and a bottom-up approach in programming. 5m Jun 2010

Explain the difference between a top-down approach and a bottom-up approach in programming. 5m Jun 2010

 

Top-down Approach

Bottom-up Approach

A top-down approach is essentially the breaking down of a program to gain insight into its compositional small program (or module) in a reverse engineering fashion. A bottom-up approach is the piecing together of module (or small program) to give rise to more complex program, thus making the original modules of the emergent program.
Structure / procedure oriented programming languages like C programming language follows top-down approach. Object oriented programming languages like C++ and JAVA programming language follows bottom-up approach.
A top-down approach begins with high level design and ends with low level design or development. A bottom-up approach begins with low level design or development and ends with high level design.
In top-down approach, main function is written first and all sub functions are called from main function thus, sub-functions are written based on the requirement In bottom-up approach, code is developed from modules and then these modules are integrated with main function

Now-a-days, both approachs are combined together and followed in modern software design.

Write a program in ‘C’ to find a sum of square of odd numbers. 6m Jun 2010

Write a program in ‘C’ to find a sum of square of odd numbers :- 12 +32+ 52+ 72 +92+ +N2

 

Code:-

#include<stdio.h>
void main()
{
int NUM,i,j,SUM=0;
clrscr();
printf(“\nENTER INTERGER NUMBER : “);
scanf(“%d”,&NUM);
for(i=1;i<NUM+1;i++)
{
if(i%2!=0)
{
SUM=SUM+(i*i);
}
}
printf(“\nTHE SUM OF SQUARE OF ODD NOS. TILL %d NO. IS : %d”,NUM,SUM);
getch();
}

 

#include<stdio.h>
void main()
{
int NUM,i,j,SUM=0;
clrscr();
printf("\nENTER INTERGER NUMBER : ");
scanf("%d",&NUM);
for(i=1;i<NUM+1;i++)
{
if(i%2!=0)
{
SUM=SUM+(i*i);
}
}
printf("\nTHE SUM OF SQUARE OF ODD NOS. TILL %d NO. IS : %d",NUM,SUM);
getch();
}

Screen Shots:-

C_program_Add_Square_Odd

 

C_program_Add_Square_Odd_Out

Write a macro to find cube of a given number. 4m Jun 2010

Write a macro to find cube of a given number. 4m

Code:

#include<stdio.h>
#define CUBE(N) (N * N * N )
void main()
{
int NUM;
clrscr();
printf(” Enter number : “);
scanf(“%d”,&NUM);
printf(“\n Cube of number is : %d “,CUBE(NUM));
getch();
}

#include<stdio.h>
#define CUBE(N) (N * N * N )
void main()
{
int NUM;
clrscr();
printf(" Enter number : ");
scanf("%d",&NUM);
printf("\n Cube of number is : %d ",CUBE(NUM));
getch();
}

Screen Shots:

C_program_Macro_Cube

C_program_Macro_Cube_Out

 

 

(c) Write a program in C, using structures to generate a report for students which display Roll No. and Name of student, total marks obtained by the student. Assumptions can be made wherever necessary.

Solved program can be found on this link http://cssimplified.com/c-programming/a-c-program-to-process-the-students-evolution-records-using-structures

 

4. (a) Write a program and flowchart to display the following pattern : 8

H

He

HeL

HeLL

HeLLO

HeLL

HeL

He

H

Solved program can be found on this link http://cssimplified.com/c-programming/write-a-program-in-c-to-print-the-following-format-10m-dec2005

Why C is called a middle level language? Give a flowchart to explain the program execution process. Explain each step in detail. 10m Jun 2010

Why C is called a middle level language? Give a flowchart to explain the program execution process. Explain each step in detail. 10

 

C is called a middle level language

It is actually binding the gap between a machine-level language and high-level language. User can use C language to do System Programming (For writing Operating System) as well as Application Programming (For generating menu driven customer billing system) that is why it is called middle level language

C is referred to as middle level language as with C we are able to manipulate bits, bytes and addresses i.e. interact with the hardware directly. We are also able to carry out memory management functions

C is a general purpose, structured programming language. Among the two types of programming languages discussed earlier, C lies in between these two categories. That’s why it is often called a middle level language. It means that it combines the elements of high level languages with the functionality of assembly language. It provides relatively good programming efficiency (as compared to machine oriented language) and relatively good machine efficiency as compared to high level languages). As a middle level language, C allows the manipulation of bits, bytes and addresses – the basic elements with which the computer executes the inbuilt and memory management functions. C code is very portable, that it allows the same C program to be run on machines with different hardware configurations. The flexibility of C allows it to be used for systems programming as well as for application programming.

C is commonly called a structured language because of structural similarities to ALGOL and Pascal. The distinguishing feature of a structured language is compartmentalization of code and data. Structured language is one that divides the entire program into modules using top-down approach where each module executes one job or task. It is easy for debugging, testing, and maintenance if a language is a structured one. C supports several control structures such as while, do-while and for and various data structures such as strucs, files, arrays etc. as would be seen in the later units. The basic unit of a C program is a function – C’s standalone subroutine. The structural component of C makes the programming and maintenance easier.

 DIAGRAMMATIC REPRESENTATION OF PROGRAM EXECUTION PROCESS

Program Execution Process

2. (a) Write a program to search an element in a given list of elements using linear search. 8

Solved program can be found on this link http://cssimplified.com/assignments/write-a-program-to-do-linear-search-for-an-integer-in-20-distinct-numbers-the-program-should-return-the-location-of-an-element-ignou-bca-assignment-2015-16

 

(b) Write a recursive program to calculate the factorial of a given number. 8

Solved program can be found on this link http://cssimplified.com/c-programming/draw-a-corresponding-flow-chart-to-find-the-factorial-of-a-given-number-using-recursion-10m-dec2008

 

(c) Give an example to explain null pointer assignment. 4

Solved program can be found on this link http://cssimplified.com/c-programming/give-a-brief-note-on-null-pointer-assignment-write-a-program-to-illustrate-this-concept-6m-jun2008

 

3. (a) Write a program in C to find the multiplication of 2 matrices of size (3 x 3). 5

Solved program can be found on this link http://cssimplified.com/c-programming/an-interactive-c-program-to-multiply-two-matrices

 

 (b) Write a macro for the following: 4×2=8

            (i) to find largest number among 3 given numbers.

Solved program can be found on this link http://cssimplified.com/c-programming/write-a-macro-to-find-the-smallest-number-among-3-given-numbers-7m-jun2007

Explain the concept of array of pointers. 5m Jun 2010

Explain the concept of array of pointers. Using pointers write a program to test whether the given string is a palindrome or not. 10

 

ARRAY OF POINTERS

The way there can be an array of integers, or an array of float numbers, similarly, there can be array of pointers too. Since a pointer contains an address, an array of pointers would be a collection of addresses. For example, a multidimensional array can be expressed in terms of an array of pointers rather than a pointer to a group of contiguous arrays.

4 5 6

7 8 9

Two-dimensional array can be defined as a one-dimensional array of integer pointers

by writing:

int *arr[3];

rather than the conventional array definition,

int arr[3][5];

Similarly, an n-dimensional array can be defined as (n-1)-dimensional array of pointers by writing

data-type *arr[subscript 1] [subscript 2]…. [subscript n-1];

The subscript1, subscript2 indicate the maximum number of elements associated with each subscript.

 

palindrome

Solved program can be found on this link http://cssimplified.com/assignments/an-interactive-c-program-to-check-whether-the-given-string-is-a-palindrome-or-not-using-pointers

 

(c) Differentiate between

            (i)Various storage classes 6

Solved program can be found on this link http://cssimplified.com/c-programming/explain-various-types-of-storage-classes-in-c-with-example-for-each

 

(ii)Structure and union 4

Solved program can be found on this link http://cssimplified.com/c-programming/what-are-the-differences-between-structure-and-union-give-example-of-usage-of-the-union-8m-jun2008

What are the precautions that must be taken care to use macros in ‘C’? 5m Dec 2009

What are the precautions that must be taken care to use macros in ‘C’?

 

Caution in using macros

You should be very careful in using Macros. In particular the textual substitution means that arithmetic expressions are liable to be corrupted by the order of evaluation rules (precedence rules). Here is an example of a macro, which won’t work.

#define DOUBLE(n) n + n

Now if we have a statement,

z = DOUBLE(p) * q;

This will be expanded to

z = p + p * q;

And since * has a higher priority than +, the compiler will treat it as.

z = p + (p * q);

The problem can be solved using a more robust definition of DOUBLE

#define DOUBLE(n) (n + n)

Here, the braces around the definition force the expression to be evaluated before any surrounding operators are applied. This should make the macro more reliable.

Explain fscanf ( ) statements with an example. 10m Dec 2009

Explain fprintf ( ) and fscanf ( )statements with an example of each. 10m Dec 2009

fscanf()

Declaration

int fscanf ( FILE * stream, const char * format, … );

Description

Read formatted data from stream

Reads data from the stream and stores them according to the parameter format into the locations pointed by the additional arguments.

The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string.

Stream

Pointer to a FILE object that identifies the input stream to read data from.

Format

C string that contains a sequence of characters that control how characters extracted from the stream are treated:

  • Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters — see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).
  • Non-whitespace character, except format specifier (%): Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a %character) causes the function to read the next character from the stream, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next character of format. If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread.
  • Format specifiers: A sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type and format of the data to be retrieved from the stream and stored into the locations pointed by the additional arguments.

format specifier for fscanf follows this prototype:

%[*][width][length]specifier

Where the specifier character at the end is the most significant component, since it defines which characters are extracted, their interpretation and the type of its corresponding argument:

specifier

Description

Characters extracted

iu Integer Any number of digits, optionally proceeded by a sign (+ or -).Decimal digits assumed by default (0-9), but a 0 prefix introduces octal digits (0-7), and 0x hexadecimal digits (0-f).
D Decimal integer Any number of decimal digits (0-9), optionally proceeded by a sign (+ or -).
O Octal integer Any number of octal digits (0-7), optionally proceeded by a sign (+ or -).
X Hexadecimal integer Any number of hexadecimal digits (0-9a-fA-F), optionally preceded by 0x or 0X, and all optionally preceded by a sign (+ or -).
feg Floating point number A series of decimal digits, optionally containing a decimal point, optionally preceeded by a sign (+ or -) and optionally followed by the e or E character and a decimal integer (or some of the other sequences supported by strtod).
Implementations complying with C99 also support hexadecimal floating-point format when preceded by 0x or 0X.
A
C Character The next character. If a width other than 1 is specified, the function reads exactlywidth characters and stores them in the successive locations of the array passed as argument. No null character is appended at the end.
s String of characters Any number of non-whitespace characters, stopping at the first whitescape character found. A terminating null character is automatically added at the end of the stored sequence.
P Pointer address A sequence of characters representing a pointer. The particular format used depends on the system and library implementation, but it is the same as the one used to format %p in fprint.
[characters] Scanset Any number of the characters specified between the brackets.
A dash (-) that is not the first character may produce non-portable behavior in some library implementations.
[^characters] Negated scanset Any number of characters none of them specified as characters between the brackets.
N Count No input is consumed.
The number of characters read so far from stream is stored in the pointed location.
% % % followed by another % matches a single %.

Except for n, at least one character shall be consumed by any specifier. Otherwise the match fails, and the scan ends there.

The format specifier can also contain sub-specifiers: asterisk (*), width and length (in that order), which are optional and follow these specifications:

sub-specifier

description

* An optional starting asterisk indicates that the data is to be read from the stream but ignored (i.e. it is not stored in the location pointed by an argument).
width Specifies the maximum number of characters to be read in the current reading operation (optional).
length One of hhhllljztL (optional).
This alters the expected type of the storage pointed by the corresponding argument (see below).

This is a chart showing the types expected for the corresponding arguments where input is stored (both with and without a length sub-specifier):

Note: Yellow rows indicate specifiers and sub-specifiers introduced by C99.

… (addittional arguments)

Depending on the format string, the function may expect a sequence of additional arguments, each containing a pointer to allocated storage where the interpretation of the extracted characters is stored with the appropriate type.
There should be at least as many of these arguments as the number of values stored by the format specifiers. Additional arguments are ignored by the function.
These arguments are expected to be pointers: to store the result of a fscanf operation on a regular variable, its name should be preceded by the reference operator (&).

RETURN VALUE

On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of theend-of-file.

If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned.

If an encoding error happens interpreting wide characters, the function sets  errno to EILSEQ.

 

(b)Write a program in ‘C’: 10

(i) To reverse a string

Solved program can be found on this link http://cssimplified.com/c-programming/a-c-program-to-reverse-the-given-string-using-recursion

 

(ii) To copy str1 to str2 without the use of strcpy function.

Solved program can be found on this link http://cssimplified.com/c-programming/write-a-program-that-does-not-use-the-inbuilt-string-functions-to-perform-the-following-10m-jun2006

What is pointer variable? How its declared? How its address is determined? How pointer can be used to pass an entire array to a function in C? 10m Dec 2009

What is pointer variable? How is a pointer variable declared? How is the address of a pointer variable determined? How pointer can be used to pass an entire array to a function in C? Explain with the help of an example. 10

An ordinary variable is a location in memory that can hold a value. For example, when you declare a variable num as an integer, the compiler sets aside 2 bytes of memory to hold the value of the integer. In your program, you refer to that location in memory by the name num. At the machine level that location has a memory address.

int num = 100;

We can access the value 100 either by the name num or by its memory address. Since addresses are simply digits, they can be stored in any other variable. Such variables that hold addresses of other variables are called Pointers. In other words, a pointer is simply a variable that contains an address, which is a location of another variable in memory.

 

A pointer variable “points to” another variable by holding its address. Since a pointer holds an address rather than a value, it has two parts. The pointer itself holds the address. That addresses points to a value. There is a pointer and the value pointed to. This fact can be a little confusing until you get comfortable with it, but once you get familiar with it, then it is extremely easy and very powerful.

We have seen in the previous section that &qty returns the address of qty and this address can be stored in a variable as shown below:

ptr = &qty;

In C, every variable must be declared for its data type before it is used. Even this holds good for the pointers too. We know that ptr is not an ordinary variable like any integer variable. We declare the data type of the pointer variable as that of the type of the data that will be stored at the address to which it is pointing to. Since ptr is a variable, which contains the address of an integer variable qty, it can be declared as:

int *ptr;

where ptr is called a pointer variable. In C, we define a pointer variable by preceding its name with an asterisk (*). The “*” informs the compiler that we want a pointer variable, i.e. to set aside the bytes that are required to store the address in memory.

The int says that we intend to use our pointer variable to store the address of an integer.

 

Example

int x; /* x is initialized to a value 10*/

p = &x; /* Pointer declaration & Assignment */

*p=10;

Let us write the complete program as shown below:

# include <stdio.h>

main( )

{

int *p; /* a pointer to an integer */

int x;

p = &x;

*p=10;

printf(“The value of x is %d”,*p);

printf(“\nThe address in which the x is stored is %d”,p);

}

 

OUTPUT

The value of x is 10

The address in which the x is stored is 52004

 

Characteristic features of Pointers:

With the use of pointers in programming,

  1. The program execution time will be faster as the data is manipulated with the help of addresses directly.
  2. Will save the memory space.
  3. The memory access will be very efficient.
  4. Dynamic memory is allocated.

 

3. (b) Write a program in ‘C’ to find whether a given number is Armstrong number or not. 10

 Similar Solved program can be found on this link http://cssimplified.com/c-programming/a-c-program-to-find-all-armstrong-numbers-in-the-range-of-0-to-999

 

4. (a) Write program in ‘C’ for the multiplication of two square matrices. 10

Similar Solved program can be found on this link http://cssimplified.com/c-programming/an-interactive-c-program-to-multiply-two-matrices