Friday, 26 May 2017

C program to reverse a number using pointer.

Question : Write a Program in c to reverse a number using pointer

\* C Program to to reverse a number using pointer *\

# include < stdio.h >
int  main( )
{
int  num, rem, rev=0 ;
int  *pn, *pr ;
printf(" Enter the number : ") ;
scanf("%f ",& num) ;

pn = & num ;
pr = & rev ;

do
{
rem = ( *pn ) % 10 ;
*pr = ( *pr * 10 ) + rem ;
*pn = ( *pn ) / 10 ;
}while(  *pn > 0) ;
printf("\n Reverse of Number is : %d ",*pr) ;
return ( 0 );
}

Output:
Enter the number:
549
Reverse of number is : 945

C program for string palindrom.

A string is said to be palindrome if it remains same after reversing it. That is, it is read same in both ways. For example: MADAM, 1001, 111 etc. are palindromes.

The following C Program will check a string is palindrome or not ! 

#include <stdio.h>
#include <string.h>

int main()
{
    int i, j, len, palindrome = 1;
    char str[80];
    printf("Enter a string: ");
    gets(str);
    len = strlen(str);
    for(i=0, j=len-1; i<j; i++, j--){
        if(str[i] != str[j]){
            palindrome = 0;
            break;
        }
    }
    if(!palindrome)
        printf("%s is not a palindrome!\n",str);
    else
        printf("%s is a palindrome!\n",str);
    return 0;
}



Output:Enter a string: MADAM.                      

MADAM is a palindrom!

how to do p programming on Android phone.

Calculate Distance of Two Points using C Structure

Let A (x1, y1) and B (x2, y2) are two points. Then the formula to calculate the distance between these two points is:
In general, we can take 4 variables x1, y1, x2, y2and calculate their distance using above formula. But it will be smarter if we use a structure that represent a single point. Here is a example program:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

struct Point {
    int x, y;
};


double getDistance(struct Point a, struct Point b)
{
    double distance;
    distance = sqrt((a.x - b.x) * (a.x - b.x) + (a.y-b.y) *(a.y-b.y));
    return distance;
}



int main()
{
    struct Point a, b;
    printf("Enter coordinate of point a: ");
    scanf("%d %d", &a.x, &a.y);
    printf("Enter coordinate of point b: ");
    scanf("%d %d", &b.x, &b.y);
    printf("Distance between a and b: %lf\n", getDistance(a, b));


    return 0;
}
Here is sample run of the program:


C program to implement Binary Search Tree (BST)

A Binary Search Tree ( BST ) is a binary tree that maintains the following property:
BST [ fig. Wikimedia ]

  1. The left subtree of a node contains only nodes with keys less than the node's key.
  2. The right subtree of a node contains only nodes with keys greater than the node's key.
  3. The left and right subtree each must also be a binary search tree.
  4. Each node can have up to two successor nodes.
  5. There must be no duplicate nodes.
  6. A unique path exists from the root to every other node.

C/C++ Implementation of BST:

The following program shows how to create and insert nodes to a Binary Search Tree.

#include <stdio.h>
#include <stdlib.h>

struct node
{
    int value;
    node* left;
    node* right;
};


struct node* root;

struct node* insert(struct node* r, int data);

int main()
{
    root = NULL;
    int n, v;

    printf("How many data's do you want to insert ?\n");
    scanf("%d", &n);

    for(int i=0; i<n; i++){
        printf("Data %d: ", i+1);
        scanf("%d", &v);
        root = insert(root, v);
    }
    return 0;
}

struct node* insert(struct node* r, int data)
{
    if(r==NULL) // BST is not created created
    {
        r = (struct node*) malloc(sizeof(struct node)); // create a new node
        r->value = data;  // insert data to new node
        // make left and right childs empty
        r->left = NULL;   
        r->right = NULL;
    }
    // if the data is less than node value then we must put this in left sub-tree
    else if(data < r->value){ 
        r->left = insert(r->left, data);
    }
    // else this will be in the right subtree
    else {
        r->right = insert(r->right, data);
    }
    return r;

}

Above program only inserts data / nodes to the binary tree. To print the tree, we need to know how to traverse a Binary Search Tree. Please visit this link to know how to traverse / print a BST.

Saturday, 20 May 2017

List and explain the precedence of Arithmetic, Logical and Relational operators in ‘C’.

C uses a certain hierarchy to solve such kind of mixed expressions. The hierarchy and associatively of the operators discussed so far is summarized in Table. The operators written in the same line have the same priority. The higher precedence operators are written first

ARITHMETIC OPERATORS

+         Addition
-          Subtraction
*          Multiplication
/          Division
%         Modular Division

Arithmetic operators are used for making mathematical expression and evaluating results in any kind of formulas by using Brackets wherever needed.

RELATIONAL OPERATORS

Operator.      CheckCondition      Meaning 

  ==                    X==Y.            X is equal toY
  !=                     X!=Y.             X is not equal                                                   to Y
  <                      X<Y.             X is less thanY      <=                     X<=Y.            X is less than    or equal to Y
>                       X>Y.               X is greater than Y
>=                     X>=Y.            X is greater than or equal to Y

Relational operators are used to check any condition by comparing the values of variables used inside a program. The result of any comparison (condition) will give you true or false only.

LOGICAL OPERATORS

Operator.              Meaning

&&                          Logical AND
||                             Logical OR
!                              Logical NOT

Logical operators (AND and OR) combine two conditions and logical NOT is used to negate the condition i.e. if the condition is true, NOT negates it to false and vice versa.

Wednesday, 17 May 2017

Photoshop Interview question


i1) What is Adobe Photoshop?
It is software developed by Adobe to create and edit images and logos. By adobe photoshop adjustment and modification can be done.
2) How you can re-size the image in Photoshop?
 To resize the image in Photoshop you have to go into menu bar, under menu bar you will find an option “Image Size”. On clicking that option, it will open a dialog box, by which you can adjust the size of the image.
3) What is a Gradient in Adobe Photoshop?
Gradients are a great way to introduce eye-catching and flashy graphics in your pages.
4) What are the Photoshop’s work areas?
The Photoshop’s work area includes Application Bar, Option Bar, Panel Dock and Tools panel.
5) In Adobe Photoshop how you can print the grid?
First of all you have to place the non-printing grid in a manner you want the print, and then take a screen shot.  Now, you have to open a new file and paste your screen shot image on it. Once done, you can crop the background of the Photoshop window except the image with the grid. The image is ready for print.
6) What is resizing images and what are the parameters to change the size of the picture?
To suit a particular purpose of the application resizing of the images is done.
The parameters to change the size of image are:
Type of image or pictureSize of pixelsBackground resolution
7) In Photoshop, what is a smart object?
In Photoshop CS2 and above, it has a special layer known as Smart Object Layer.  Smart objects give freedom to work with multiple copies of a single object. All the multiple copies will be updated simultaneously when single object is updated. Also, changes in the adjustment of layers and layer styles of a single object can be done without affecting the multiple copies. Without any loss in pixel, pixel based objects can be changed several times.
8) How do you organize layers in Photoshop?
A layers shows a picture or image. To organize layers in Photoshop, place various images in separate layers. Lock the unused layers and unlock the layers which are in use. When two or more layers need to be changed, unlock the layers.
9) How you can unlock the background in Photoshop?
To unlock the background image, first click on the picture or image and then select MODE option.  After that, select the option GRAY SCALE and revert to LAYER. When you double click on the surface, the surface will be unlocked.
10) How do you select an exact color to match?
To sample the color as foreground color, we use the eye-dropper tool.   Select the foreground color square, use the paint bucket tool or brush tool for covering the area. You can also use Clone Stamp Tool.  Now use the key Alt+ and click where you want the color from and hold down the mouse button to cover up the area.
11) What is the difference between PSB (Photoshop Big) and PSD (Photoshop Document)?
They both are file formats to store digital images.  There is very less difference between PSB and PSD, what they differ is how they are stored and used.  PSD is a default extension for Photoshop files and it can support the file size of 30,000 by 30,000 pixels. While for creating big documents or large image .psb file format is used, and it can save an image size upto 300,000 by 300,000 pixels.
12) What is healing tool?
Healing tool is used in Photoshop to hide the unwanted spots or pictures that appeared in your original picture and makes picture look like real without any changes.  The tool use complicated algorithm to calculate what would be the area of your picture based on the surrounding pixels.
13) Can you use bamboo tablet in Photoshop?
Yes, you can use bamboo tablet in Photoshop.  After installing the bamboo tablet software, open the software. Once done, the next step is to configure the four hotkeys of Bamboo tablet with the help of the software available in tablet. Create a new document and open the Photoshop, you can now have Photoshop with a bamboo tablet.
14) How can you reduce noise in an image?
Reduce noise option is helpful to reduce the color and luminance effect in the image. To reduce the noise in an image, you have to go in a menu bar, select a filter menu, and in that you will see an option for NOISE. Again, clicking on it, it will show other option including reducing noise.
15) How to create an artistic border?
To create an artistic border, you must select an image. After that, add a layer mask in a layer pallet then select filter-> brush strokes-> sprayed strokes.
16) What is a Gaussian blur?
Gaussian blur is a tool that blurs the edges of the image to make it more real and adaptive to the surrounding. Often it is believed that Gaussian blur can only blurs the image, but if it is used cleverly it will not blurs the image but enhance the appearance.
17) What are swatches palettes?
Photoshop provides two palettes for selecting color, a) Swatch Palettes  b) Color Palettes.  Some specific colors can be used without remembering the numeric color values. Also, colors can be extracted from an available image. Default swatches and custom swatches are also an additional option for the users.
18)What are Lasso tools and name them?
With lasso tools precise area of an image can be selected, just by tracing the selection outlines the areas are selected.
Simple Lasso ToolPolygonal Lasso ToolMagnetic Lasso Tool
19)  With the help of spin software how you can make 3D sphere?
To make 3D sphere, select blur from filter menu and click on radial blur.  Select spin option in the blur method section, you can increase or decrease the amount of spin by dragging the slider.
20) How to create a transparent background in Photoshop?
To create a transparent image you need to follows three steps:
First go to ‘Select’ option and select the background, and then click on ‘Inverse’. This will select your main picture.Open a new file, select option ‘ Transparent’ under content, and you will have a file with transparent background.Copy your main picture and paste it to new file you created.
21) What is Clone tool?
Clone tool uses the current brush to repair the problem areas in photos and pictures, by painting over them with pixel data from other areas.
22) How you fix the blurry images in Photoshop?
To fix the blurry images in Photoshop you can use sharpening tools. Sharpening the image will lose the pixels, make sure you are finished with everything else and saved the changes before you start sharpening the image.
23) What tool you can use to combine images?
You can use Auto-blend layers command to combine images. Auto-blend layers uses layer masks as needed to mask-out over underexposed areas.
24) What is a Bezier curve?
It is a mathematically defined curve used in two-dimensional graphic applications. It is defined by four points, the initial position, two middle point positions and a terminating position.
25) How does Red Eye tool works?
Red eye tool is a type of a repairing tool. When you circle any problematic area with red eye tool, the Photoshop will automatically identity that area and will replace it by dark-gray pixels.
26) Explain what is PostScript and showpage command?
PostScript is a page description language developed by Adobe Systems. It is a language for printing documents on laser printer, but it can also be used to produce images on other types of devices.
Showpage command transfers the contents of the current page to the current output device.
The main function of showpage is
• It executes the endpage procedure in the page device dictionary
• Executes the function equivalent of an initgraphics operation, reinitializing the graphics state for the next page
• In page device dictionary, it executes the beginpage
• If the Boolean result returned by the EndPage process is true, transmits the contents of the page to the current output device and performs the equivalent of an erasepage operation, clearing the contents in preparation for the next page.
27) Define what is the meaning of a Path?
A path can be defined as a collection of possibly disconnected, lines and areas describing the image. In simple words, it is a collection of curves and line segments arranged on the page. A path cannot be drawn by itself, but after it is specified it can be stroked (lines) or filled (places) making the proper marks.
28) Explain what is Photoshop lightroom?
Photoshop light room is a software designed for photographer to make post-processing work easy after photography.
Key features in Light room  are
PNG SupportFull Screen ModeUser Configurable Grid OverlaysWindows HiDPI Support
29) Explain how you can import photographs in Lightroom from hard-drives?
When you start lightroom, it automatically ready itself for immediate import as soon as you connect an external storage device to your computer. But it fails then you have to follow the steps below.
First select the source to import images file formSecond step includes selecting files which one you want to importOnce you select the files, you have to specify the method of import for example like Copy as DNG, Copy, Move , Add etc.The last step is to choose the destination to copy files to, file handling options and meta-data setting. This step is little longer than other steps as it includes other steps like file handling, file re-naming, apply during import etc.
30) Explain how you can create a Diptych?
To create a Diptych
Go to “Print” module under the main menuUnder layout style select Custom PackageNow under Rulers, Grids and Guides , check and uncheck the options as per your requirement like page grid, rulers, image cells, dimensions etc.After that adjust other settings like file resolution, custom file dimensions, JPEG QualityNow you can drag and drop the images on your film strip onto the blank page and arrange themWhen done, choose print to file to export your diptych

Multimedia interview question

Question: What is a ambeant acclusion? 

Answer: Ambient occlusion is a shading method used in 3D computer graphics which helps add realism to local reflection models by taking into account.
Ambient Occlusion is a method for simulating global
illumination, while keeping a respectable ratio between results. Source: CoolInterview.com 

More Answers

Question: What are Multimedia Softwares? 

Answer: The software used to create multimedia experiences can be placed into 3 distinct categories:

* Audio Software
* Graphics Software
* Video Software
Source: CoolInterview.com 

More Answers

Question: What is animation? 

Answer: Animation is the rapid display of a sequence of images of 2-D or 3-D artwork or model positions in order to create an illusion of movement. Source: CoolInterview.com 

More Answers

Question: What is meaning of multimedia? 

Answer: Multimedia is simply multiple forms of media(text and graphics and sound etc)integrated together.
Source: CoolInterview.com 

More Answers

Question: What is animation? 

Answer: Animation is the rapid display of a sequence of images of 2-D or 3-D artwork or model positions in order to create an illusion of movement.
Source: CoolInterview.com 

More Answers

Question: What is meaning of multimedia? 

Answer: Multimedia is simply multiple forms of media(text and graphics and sound etc)integrated together.
Source: CoolInterview.com 

More Answers

Question: What is mean by Rigging? 

Answer: Rigging is a method of attaching bones or biped to a
'modeled character' or object in order to make them animate or 'perform' actions. By attaching bones or biped the 'character' can walk,talk and make bodily movements.
Source: CoolInterview.com 

More Answers

Question: What are Multimedia Hardwares? 

Answer: Multimedia hardware basically consists of video and sound cards, and cd-rom drives. To make it a little easier multimedia kits are available that include all the necessary hardware and software to upgrade your present computer(s).
Source: CoolInterview.com 

More Answers

Question: What is the arc in animation? 

Answer: arc is known as a curve which determine the poses of the character, it is the most important concept for animation.
To get good knowledge on arc u must have drawing skills Source: CoolInterview.com 

More Answers

Question: What are the Multimedia Authoring Tools? 

Answer: Multimedia authoring tools make it easier to create full scale multimedia projects. Fortunately, there are an assortment of tools available to choose from.

► Apple Media Tool
► Astound
► Asymetric Multimedia ToolBook
► Authorware
► Cinemation
► Course Builder
► cT Professional
► Digital Chisel
► Director
► Director Multimedia Studio
► FireWalker
► Formula Graphics
► HM-Card Hy Source: CoolInterview.com 

Bca 1st nd 2nd sem Datesheet 2017

Tuesday, 16 May 2017

C-processors

The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. We'll refer to the C Preprocessor as CPP.

All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character, and for readability, a preprocessor directive should begin in the first column. The following section lists down all the important preprocessor directives −

DirectiveDescription
#defineSubstitutes a preprocessor macro.#includeInserts a particular header from another file.#undefUndefines a preprocessor macro.#ifdefReturns true if this macro is defined.#ifndefReturns true if this macro is not defined.#ifTests if a compile time condition is true.#elseThe alternative for #if.#elif#else and #if in one statement.#endifEnds preprocessor conditional.#errorPrints error message on stderr.#pragmaIssues special commands to the compiler, using a standardized method.

Preprocessors Examples

Analyze the following examples to understand various directives.

#define MAX_ARRAY_LENGTH 20

This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use #define for constants to increase readability.

#include <stdio.h>
#include "myheader.h"

These directives tell the CPP to get stdio.h fromSystem Libraries and add the text to the current source file. The next line tells CPP to getmyheader.h from the local directory and add the content to the current source file.

#undef FILE_SIZE
#define FILE_SIZE 42

It tells the CPP to undefine existing FILE_SIZE and define it as 42.

#ifndef MESSAGE #define MESSAGE "You wish!" #endif

It tells the CPP to define MESSAGE only if MESSAGE isn't already defined.

#ifdef DEBUG
/* Your debugging statements here */
#endif

It tells the CPP to process the statements enclosed if DEBUG is defined. This is useful if you pass the -DDEBUG flag to the gcc compiler at the time of compilation. This will define DEBUG, so you can turn debugging on and off on the fly during compilation.

Predefined Macros

ANSI C defines a number of macros. Although each one is available for use in programming, the predefined macros should not be directly modified.

MacroDescription__DATE__The current date as a character literal in "MMM DD YYYY" format.__TIME__The current time as a character literal in "HH:MM:SS" format.__FILE__This contains the current filename as a string literal.__LINE__This contains the current line number as a decimal constant.__STDC__Defined as 1 when the compiler complies with the ANSI standard.

Let's try the following example −

#include <stdio.h>
main()
{
printf("File :%s\n", __FILE__ ); printf("Date :%s\n", __DATE__ ); printf("Time :%s\n", __TIME__ ); printf("Line :%d\n", __LINE__ ); printf("ANSI :%d\n", __STDC__ );
}

When the above code in a file test.c is compiled and executed, it produces the following result −

File :test.c Date :Jun 2 2012 Time :03:36:24 Line :8 ANSI :1

Preprocessor Operators

The C preprocessor offers the following operators to help create macros −

The Macro Continuation (\) Operator

A macro is normally confined to a single line. The macro continuation operator (\) is used to continue a macro that is too long for a single line. For example −

#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")

The Stringize (#) Operator

The stringize or number-sign operator ( '#' ), when used within a macro definition, converts a macro parameter into a string constant. This operator may be used only in a macro having a specified argument or parameter list. For example −

#include <stdio.h>
#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")
int main(void)
{
message_for(Carole, Debra);
return 0;
}

When the above code is compiled and executed, it produces the following result −

Carole and Debra: We love you!

The Token Pasting (##) Operator

The token-pasting operator (##) within a macro definition combines two arguments. It permits two separate tokens in the macro definition to be joined into a single token. For example −

#include <stdio.h>
#define tokenpaster(n)
printf ("token" #n " = %d", token##n)
int main(void)
{
int token34 = 40;
tokenpaster(34);
return 0;
}

When the above code is compiled and executed, it produces the following result −

token34 = 40

It happened so because this example results in the following actual output from the preprocessor −

printf ("token34 = %d", token34);

This example shows the concatenation of token##n into token34 and here we have used bothstringize and token-pasting.

The Defined() Operator

The preprocessor defined operator is used in constant expressions to determine if an identifier is defined using #define. If the specified identifier is defined, the value is true (non-zero). If the symbol is not defined, the value is false (zero). The defined operator is specified as follows −

#include <stdio.h>
#if !defined (MESSAGE)
#define MESSAGE "You wish!"
#endif
int main(void)
{
printf("Here is the message: %s\n", MESSAGE);
return 0;
}

When the above code is compiled and executed, it produces the following result −

Here is the message: You wish!

Parameterized Macros

One of the powerful functions of the CPP is the ability to simulate functions using parameterized macros. For example, we might have some code to square a number as follows −

int square(int x) { return x * x; }

We can rewrite above the code using a macro as follows −

#define square(x) ((x) * (x))

Macros with arguments must be defined using the#define directive before they can be used. The argument list is enclosed in parentheses and must immediately follow the macro name. Spaces are not allowed between the macro name and open parenthesis. For example −

#include <stdio.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
int main(void)
{
printf("Max between 20 and 10 is %d\n", MAX(10, 20));
return 0;
}

When the above code is compiled and executed, it produces the following result −

Max between 20 and 10 is 20

Monday, 15 May 2017

Header file: stdlib

The stdlib.h header defines four variable types, several macros, and various functions for performing general functions.

Library Variables

Following are the variable types defined in the header stdlib.h:

S.N.Variable & Description1

size_t

This is the unsigned integral type and is the result of the sizeof keyword.

2

wchar_t

This is an integer type of the size of awide character constant.

3

div_t

This is the structure returned by the divfunction.

4

ldiv_t

This is the structure returned by the ldivfunction.

Library Macros

Following are the macros defined in the header stdlib.h:

S.N.Macro & Description1

NULL

This macro is the value of a null pointer constant.

2

EXIT_FAILURE

This is the value for the exit function to return in case of failure.

3

EXIT_SUCCESS

This is the value for the exit function to return in case of success.

4

RAND_MAX

This macro is the maximum value returned by the rand function.

5

MB_CUR_MAX

This macro is the maximum number of bytes in a multi-byte character set which cannot be larger than MB_LEN_MAX.

Library Functions

Following are the functions defined in the header stdio.h:

S.N.Function & Description1

double atof(const char *str)

Converts the string pointed to, by the argument str to a floating-point number (type double).

2

int atoi(const char *str)

Converts the string pointed to, by the argument str to an integer (type int).

3

long int atol(const char *str)

Converts the string pointed to, by the argument str to a long integer (type long int).

4

double strtod(const char *str, char **endptr)

Converts the string pointed to, by the argument str to a floating-point number (type double).

5

long int strtol(const char *str, char **endptr, int base)

Converts the string pointed to, by the argument str to a long integer (type long int).

6

unsigned long int strtoul(const char *str, char **endptr, int base)

Converts the string pointed to, by the argument str to an unsigned long integer (type unsigned long int).

7

void *calloc(size_t nitems, size_t size)

Allocates the requested memory and returns a pointer to it.

8

void free(void *ptr

Deallocates the memory previously allocated by a call to calloc, malloc, orrealloc.

9

void *malloc(size_t size)

Allocates the requested memory and returns a pointer to it.

10

void *realloc(void *ptr, size_t size)

Attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc.

11

void abort(void)

Causes an abnormal program termination.

12

int atexit(void (*func)(void))

Causes the specified function func to be called when the program terminates normally.

13

void exit(int status)

Causes the program to terminate normally.

14

char *getenv(const char *name)

Searches for the environment string pointed to by name and returns the associated value to the string.

15

int system(const char *string)

The command specified by string is passed to the host environment to be executed by the command processor.

16

void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *))

Performs a binary search.

17

void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))

Sorts an array.

18

int abs(int x)

Returns the absolute value of x.

19

div_t div(int numer, int denom)

Divides numer (numerator) by denom (denominator).

20

long int labs(long int x)

Returns the absolute value of x.

21

ldiv_t ldiv(long int numer, long int denom)

Divides numer (numerator) by denom (denominator).

22

int rand(void)

Returns a pseudo-random number in the range of 0 to RAND_MAX.

23

void srand(unsigned int seed)

This function seeds the random number generator used by the function rand.

24

int mblen(const char *str, size_t n)

Returns the length of a multibyte character pointed to by the argument str.

25

size_t mbstowcs(schar_t *pwcs, const char *str, size_t n)

Converts the string of multibyte characters pointed to by the argument strto the array pointed to by pwcs.

26

int mbtowc(whcar_t *pwc, const char *str, size_t n)

Examines the multibyte character pointed to by the argument str.

27

size_t wcstombs(char *str, const wchar_t *pwcs, size_t n)

Converts the codes stored in the arraypwcs to multibyte characters and stores them in the string str.

28

int wctomb(char *str, wchar_t wchar)

Examines the code which corresponds to a multibyte character given by the argument wchar.

C-library Function: calloc()

Description

The C library function void *calloc(size_t nitems, size_t size) allocates the requested memory and returns a pointer to it. The difference in malloc andcalloc is that malloc does not set the memory to zero where as calloc sets allocated memory to zero.

Declaration

Following is the declaration for calloc() function.

void *calloc(size_t nitems, size_t size)

Parameters

nitems -- This is the number of elements to be allocated.

size -- This is the size of elements.

Return Value

This function returns a pointer to the allocated memory, or NULL if the request fails.

Example

The following example shows the usage of calloc() function.

#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, n; int *a;
printf("Number of elements to be entered:");
scanf("%d",&n);
a = (int*)calloc(n, sizeof(int)); printf("Enter %d numbers:\n",n);
for( i=0 ; i < n ; i++ )
{
scanf("%d",&a[i]);
}
printf("The numbers entered are: "); for( i=0 ; i < n ; i++ )
{
printf("%d ",a[i]); } free( a ); return(0);
}

Let us compile and run the above program that will produce the following result:

Number of elements to be entered:3 Enter 3 numbers: 22 55 14 The numbers entered are: 22 55 14

C-library function- malloc()

Description

The C library function void *malloc(size_t size)allocates the requested memory and returns a pointer to it.

Declaration

Following is the declaration for malloc() function.

void *malloc(size_t size)

Parameters

size -- This is the size of the memory block, in bytes.

Return Value

This function returns a pointer to the allocated memory, or NULL if the request fails.

Example

The following example shows the usage of malloc() function.

#include <stdio.h>
#include <stdlib.h>
int main()
{
char *str;   
/* Initial memory allocation */
str = (char *) malloc(15);
strcpy(str, "tutorialspoint");
printf("String = %s, Address = %u\n", str, str);
/* Reallocating memory */
str = (char *) realloc(str, 25);
strcat(str, ".com");
printf("String = %s, Address = %u\n", str, str);
free(str);
return(0);
}

Let us compile and run the above program that will produce the following result:

String = tutorialspoint, Address = 355090448 String = tutorialspoint.com, Address = 355090448

Saturday, 13 May 2017

C Recursion

Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function.

void recursion() {
   recursion(); /* function calls itself */
}

int main() {
   recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop.

Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of a number, generating Fibonacci series, etc.

Number Factorial
The following example calculates the factorial of a given number using a recursive function −

#include <stdio.h>

int factorial(unsigned int i) {

   if(i <= 1) {
      return 1;
   }
   return i * factorial(i - 1);
}

int  main() {
   int i = 15;
   printf("Factorial of %d is %d\n", i, factorial(i));
   return 0;
}
When the above code is compiled and executed, it produces the following result −

Factorial of 15 is 2004310016
Fibonacci Series
The following example generates the Fibonacci series for a given number using a recursive function −

#include <stdio.h>

int fibonacci(int i) {

   if(i == 0) {
      return 0;
   }

   if(i == 1) {
      return 1;
   }
   return fibonacci(i-1) + fibonacci(i-2);
}

int  main() {

   int i;

   for (i = 0; i < 10; i++) {
      printf("%d\t\n", fibonacci(i));
   }

   return 0;
}
When the above code is compiled and executed, it produces the following result −

C - Variable Arguments
Previous Page Next Page 
Sometimes, you may come across a situation, when you want to have a function, which can take variable number of arguments, i.e., parameters, instead of predefined number of parameters. The C programming language provides a solution for this situation and you are allowed to define a function which can accept variable number of parameters based on your requirement. The following example shows the definition of such a function.

int func(int, ... ) {
   .
   .
   .
}

int main() {
   func(1, 2, 3);
   func(1, 2, 3, 4);
}
It should be noted that the function func() has its last argument as ellipses, i.e. three dotes (...) and the one just before the ellipses is always an int which will represent the total number variable arguments passed. To use such functionality, you need to make use of stdarg.h header file which provides the functions and macros to implement the functionality of variable arguments and follow the given steps −

Define a function with its last parameter as ellipses and the one just before the ellipses is always an int which will represent the number of arguments.

Create a va_list type variable in the function definition. This type is defined in stdarg.h header file.

Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro va_start is defined in stdarg.h header file.

Use va_arg macro and va_list variable to access each item in argument list.

Use a macro va_end to clean up the memory assigned to va_list variable.

Now let us follow the above steps and write down a simple function which can take the variable number of parameters and return their average −

#include <stdio.h>
#include <stdarg.h>

double average(int num,...) {

   va_list valist;
   double sum = 0.0;
   int i;

   /* initialize valist for num number of arguments */
   va_start(valist, num);

   /* access all the arguments assigned to valist */
   for (i = 0; i < num; i++) {
      sum += va_arg(valist, int);
   }

   /* clean memory reserved for valist */
   va_end(valist);

   return sum/num;
}

int main() {
   printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2,3,4,5));
   printf("Average of 5, 10, 15 = %f\n", average(3, 5,10,15));
}
When the above code is compiled and executed, it produces the following result. It should be noted that the function average() has been called twice and each time the first argument represents the total number of variable arguments being passed. Only ellipses will be used to pass variable number of arguments.

Average of 2, 3, 4, 5 = 3.500000
Average of 5, 10, 15 = 10.000000