answersLogoWhite

0

📱

C Programming

Questions related to the C Computer Programming Language. This ranges all the way from K&R to the most recent ANSI incarnations. C has become one of the most popular languages today, and has been used to write all sorts of things for nearly all of the modern operating systems and applications. It it a good compromise between speed, power, and complexity.

9,649 Questions

What is the logic for random number generator in C programming?

There are many different ways of generating pseudo random numbers. Some of them are good. Some of them are not so good. It depends on the application. For a good read on this topic, I suggest "The Art Of Computer Programming", Donald E. Knuth, Volume 2, Seminumerical Algorithms.

One of the simpler way of generating pseudo random numbers is the linear congruential generator, wherein XN+1 = (AXN + B) mod C. Of course, the choice of A, B, and C is crucial to a successful implementation. Knuth has a lot to say about this generator, including the fact that it is sequentially correlated and, thus, not well suited for some applications. Nevertheless, many random number generators use this method, and they use some techniques for minimizing correlation and maximizing period. The technique used in one of the Microsoft Visual Studio runtime libraries has A=0x343FD, B=0x269EC3, and C=0x100000000, however, the return value is the value of X right shifted 16 places and AND'ed with 0x7FFF, forcing a return value between 0 and 32767, but a period much larger than that.

int rand(unsigned *seed) { /* assumes unsigned is 32 bits */

*seed = *seed * 0x343FD + 0x269EC3;

return (*seed >> 16) & 32767;

}

Do all elements in a multidimensional array have the same data type?

That really depends on the programming language. In Java, the answer is basically "yes", although if you choose the "Object" data type you could probably accomodate different data types.

If you need collections of different data types - again, assuming Java - it is probably better to use some other structures, for better organization. For example, you can organize different data types into an object. Then you can collect various of those in an array. As an example, you can create an array of objects of a class "Person"; and you this class so that each Person has an age (type int), a name (type String), and any other information you need for your specific application.

Why is pseudo code called false code?

Pseudo code cannot be processed by a machine, it is solely intended for processing by humans.

To count the number of characters in the given text file in unix?

Look at the "wc" command's man page, it will give you a count of all characters, including the newline character.

Example of lazy copy in c plus plus?

Lazy copying is a hybrid of the standard shallow-copy and deep-copy mechanisms. Objects that are copy constructed or assigned from existing instances will initially be shallow-copied, meaning their dynamic data members will share the same memory. When an object is mutated whilst sharing memory, its data will be deep copied so as not to affect the shared instances.

In other words, deep-copying is postponed until it is actually required (if at all). For large and complex objects, this can offer a significant memory saving and a major performance boost as a shallow copy is significantly faster than a deep copy, and sharing memory obviously consumes less memory.

In order to implement lazy copying, it is necessary for each instance to be fully aware of all the instances it shares memory with. One of the simplest ways of achieving that is for each instance to maintain bi-directional pointers, similar to those you would find in a doubly-linked list. However, unlike a linked list, there is no need to expose these pointers outside of the class as the class can link and unlink all by itself, via the copy constructor and the assignment operator. All the functionality is encapsulated within the class so the lazy copy mechanism is completely transparent to the end user.

The following implementation provides a brief demonstration of how the mechanism works. It is by no means a complete implementation as it can only handle one type of data, but it serves to demonstrate the key aspects of lazy copying. A more complete implementation would change the data to a template class, thus allowing any type of data to be lazy copied.

The output shows that while each instance of the object occupies separate memory locations, the data they contain is initially shared. We then manipulate the objects to show that deep copying is occurring when it is required, and that destroying a share doesn't affect any remaining shares. If you strip away the trace code in the main function you will see that the lazy copy mechanism is completely transparent; you need never know it exists as it is fully encapsulated within the Object class itself.

// Demonstration of a lazy copy mechanism

// Copyright ©PCForrest, 2012

#include <iostream>

using namespace std;

// Example data container.

class Data

{

friend ostream& operator<<(ostream& os, const Data& data);

public:

inline ~Data(){delete(m_num);}

inline Data():m_num(new int(0)){}

inline Data(const int num):m_num(new int(num)){}

inline Data(const Data& data):m_num(new int(*data.m_num)){}

inline Data& operator=(const Data& data){*m_num=*data.m_num; return(*this);}

inline Data& operator=(const int num){*m_num=num; return(*this);}

inline bool operator==(const Data& data){return(*m_num==*data.m_num);}

inline bool operator!=(const Data& data){return(*m_num!=*data.m_num);}

inline int operator+(const Data& data){return(*m_num+*data.m_num);}

inline int operator+(const int num){return(*m_num+num);}

inline Data& operator+=(const Data& data){*m_num+=*data.m_num; return(*this);}

inline Data& operator+=(const int num){*m_num+=num; return(*this);}

inline int GetNum()const{return(*m_num);}

inline void SetNum(const int num){*m_num=num;}

private:

int * m_num;

};

// Friend function

ostream& operator<<(ostream& os, const Data& data)

{

os<<"Data:0x"<<&data<<" ("<<*data.m_num<<")";

return(os);

}

// Lazy copy class.

class Object

{

friend ostream& operator<<(ostream& os, const Object& object);

public:

inline Object():m_nextshare(NULL),m_prevshare(NULL),m_data(new Data(0)){}

inline Object(const Object& object):m_prevshare(&object.LocateLastShare()),m_nextshare(NULL),m_data(object.m_data){m_prevshare->m_nextshare=this;}

inline ~Object(){if(IsShared())UnlinkShare();else delete( m_data ); m_data = NULL;}

Object& operator=(const Object& object);

Object& operator+=(const Object& object);

inline Data GetData()const{return( *m_data);}

void SetData(const Data& data);

private:

inline bool IsShared()const{return(m_prevshare!=NULL m_nextshare!=NULL);}

Object& LocateLastShare()const;

Object* LocateShare(const Object & object)const;

void UnlinkShare();

mutable Object * m_nextshare;

mutable Object * m_prevshare;

Data * m_data;

};

// Friend function

ostream& operator<<(ostream& os, const Object& object)

{

os<<"Object:0x"<<&object<<"\t"<<*object.m_data;

return(os);

}

// Assign (implements shallow-copy)

Object& Object::operator=(const Object& object)

{

if( &object != this && // Not a self-reference.

!LocateShare(object) ) // Not already shared.

{

// Unlink or destroy data.

if( IsShared() )

UnlinkShare();

else if( m_data )

delete( m_data );

// Shallow-copy.

m_data = object.m_data;

// Link to new shares.

m_prevshare = &object.LocateLastShare();

m_prevshare->m_nextshare = this;

}

return(*this);

}

// Add/assign (implements deep-copy)

Object& Object::operator+=(const Object& object)

{

if( IsShared() )

{

UnlinkShare();

m_data = new Data( *m_data + *object.m_data );

}

else

*m_data += *object.m_data;

return( *this );

}

// Returns a reference to the last shared instance of this instance.

Object& Object::LocateLastShare()const

{

Object* p=(Object*)this;

while(p && p->m_nextshare)

p=p->m_nextshare;

return(*p);

}

// Returns a pointer to the given object if it is amongst the shared instances

// of this instance. Returns NULL if the object is this instance or is not shared.

Object* Object::LocateShare(const Object& object)const

{

// Search previous instances first.

Object* p=m_prevshare;

while( p && p!=&object)

p=p->m_prevshare;

if(!p)

{

// Not found, search next instances:

p = m_nextshare;

while( p && p!=&object) p=p->m_nextshare;

}

return(p);

}

// Unlinks this object from its shared instances.

void Object::UnlinkShare()

{

// Update the links on either side first.

if(m_nextshare) m_nextshare->m_prevshare=m_prevshare;

if(m_prevshare) m_prevshare->m_nextshare=m_nextshare;

m_nextshare=NULL;

m_prevshare=NULL;

}

// Mutator. Implements deep copy if incoming data differs.

void Object::SetData(const Data& data)

{

if( *m_data != data )

{

if( IsShared() )

{

UnlinkShare();

m_data = new Data(data);

}

else

*m_data = data;

}

}

// Demonstration program:

int main()

{

Object a;

a.SetData( 5 );

Object b = a; // Assign (lazy copy)

Object* c = new Object(b); // Copy construct (lazy copy)

cout<<"Original memory:"<<endl;

cout<<"a\t"<<a<<endl;

cout<<"b\t"<<b<<endl;

cout<<"c\t"<<*c<<endl;

cout<<endl;

b += a; // Deep copy.

cout<<"After mutating b:"<<endl;

cout<<"a\t"<<a<<endl;

cout<<"b\t"<<b<<endl;

cout<<"c\t"<<*c<<endl;

cout<<endl;

delete(c);

cout<<"After destroying c:"<<endl;

cout<<"a\t"<<a<<endl;

cout<<"b\t"<<b<<endl;

cout<<endl;

// Instantiate a new, unshared instance

c = new Object();

cout<<"After instantiating c as new:"<<endl;

cout<<"a\t"<<a<<endl;

cout<<"b\t"<<b<<endl;

cout<<"c\t"<<*c<<endl;

cout<<endl;

// Assign b to c

*c = b;

cout<<"After reassigning c:"<<endl;

cout<<"a\t"<<a<<endl;

cout<<"b\t"<<b<<endl;

cout<<"c\t"<<*c<<endl;

cout<<endl;

return(0);

}

Output:

Original memory:

a Object:0x001FFA20 Data:0x003577B8 (5)

b Object:0x001FFA0C Data:0x003577B8 (5)

c Object:0x00211F58 Data:0x003577B8 (5)

After mutating b:

a Object:0x001FFA20 Data:0x003577B8 (5)

b Object:0x001FFA0C Data:0x00357818 (10)

c Object:0x00211F58 Data:0x003577B8 (5)

After destroying c:

a Object:0x001FFA20 Data:0x003577B8 (5)

b Object:0x001FFA0C Data:0x00357818 (10)

After instantiating c as new:

a Object:0x001FFA20 Data:0x003577B8 (5)

b Object:0x001FFA0C Data:0x00357818 (10)

c Object:0x00211F58 Data:0x003578A8 (0)

After reassigning c:

a Object:0x001FFA20 Data:0x003577B8 (5)

b Object:0x001FFA0C Data:0x00357818 (10)

c Object:0x00211F58 Data:0x00357818 (10)

What are some examples of simple programs that use different iteration statements to find the average academic marks of 100 students?

struct student
{
nt regno,mark[4],avg;
char name[10];
};
void main()
{
student s[100];
int i,j,t=0;
printf("enter student DETAILES\n");
for(i=0;i<100;i++)
{
printf("ENTER REGISTER NO : ");
scanf("%d",&s[i].regno);
printf("ENTER NAME : ");
scanf("%s",s[i].name);
printf("ENTER FOUR MARKS \n");
s[i].avg=0;
for(j=0;j<4;j++)
{
scanf("%d",&s[i].mark[j]);
t=t+s[i].mark[j];
}
s[i].avg=t/100;
}
printf("THE STUDENTS INFORMATION \N");
for(i=0;i<100;i++)
{
printf("\n REGISTER NUMBER : %d",s[i].regno);
printf("\n NAME : %s",s[i].name);
printf("\n AVERAGE MARK : %d",s[i].avg);
}
getch();
}

What is a type of spam that collects data from a user without his knowledge?

Spyware is a software that collects information from the user without their knowledge. It also called spybot or tracking software if it is obtained from the internet. Many of these software get automatically installed into the computer as a virus software or as a result of downloading materials from untrusted sources. They may also be installed when some of the deceptive add pop-ups on the internet are clicked.

What is an H2B swap?

H-series engine mated with a B-series transmission using an adaptor plate.

Using C programming language design a menu driven programme that will draw a straight line?

#include<stdio.h>

#include<conio.h>

int main()

{

int i=0,opt;

printf("Enter your choice\n");

printf("1. Horizontal line");

printf("\n2. Vertical line\n");

scanf("%d",&opt);

if(opt==1)

{

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

printf("%c",196);

}

else

{

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

printf("%c\n",179);

}

return 0;

}

Is 10e10 can be used in c?

Yes, as a floating point constant.

What do the Tellers of Parliament count the number of?

Parliamentary Tellers are MPs or Peers that count the votes during a division (vote) and then announce the result.

What is Arrays of Pointers?

An array of pointers is a contiguous block of memory that contains pointers to other memory locations. They essentially allow non-contiguous memory locations to be treated as if they were an actual array.

What is a sequence of characters?

A sequence of characters is an array of type char, commonly known as a string.

How are three dimensional arrays represented in memory Explain how address of an element is calculated in three dimensional array?

Assuming the array is mapped in contiguous memory, the memory block is divided into equal blocks according to the first dimension, and each of those blocks is divided equally according to the second dimension. The smallest blocks therefore represent a one-dimensional array according to the final dimension.

To look at it another way, a three-dimensional array is a one-dimensional array where every element is a two-dimensional array. And every two-dimensional array is a one-dimensional array where every element is also a one-dimensional array. This concept can also be extended to four-dimensional arrays and beyond (a four-dimensional array being a one-dimensional array where every element is a three-dimensional array).

The address of any element in a contiguous multi-dimensional array is calculated from the type of element in the array and the element index.

If we assume the following three-dimensional array has been declared:

int a[3][4][5];

If we also assume that an int (integer) is a 32-bit value and a byte has 8 bits, then it can be seen there are 3*4*5*32 bits allocated to the array, which is 1920 bits in total or 240 bytes. We can also say that there are 3 arrays of 4*5 integers or, more simply, 3*4 arrays of 5 integers. An array of 5 integers therefore consumes 5*32 bits, which is 160 bits or 20 bytes. The second dimension tells us there are 4 such arrays, which makes 80 bytes, and the third dimension tells us there are 3 of those, which brings us to 240 bytes.

Thus to locate any element, we multiply the last index by 4 (the size of an integer), the middle index by 20 (the size of 5 integers) and the first index by 80 (the size of 20 integers), and add these three results together to obtain the offset from the start of the array. Thus element a[2][3][4] will be found (2*80)+(3*20)+(4*4) bytes from the start of the array, which is 160+60+16 or 236 bytes. This is the address of the last integer in the array, which is fortunate because a[2][3][4] is also the index of the last integer in the array (remember that array indices are zero-based).

The name of the array is also a reference to the start address of the array, thus the start address is a, which is the same as saying the address of element a[0][0][0], which is at offset (0*80)+(0*20)+(0*4), which is obviously 0 bytes from a.

As well as accessing elements by their indices, we can also point at individual elements using pointer arithmetic. Element a[1][2][3] can therefore be found at memory address a+(1*80)+(2*20)+(3*4), which is a+132 bytes. In point of fact, the index notation is simply syntactic sugar for the pointer arithmetic that is actually done behind the scenes.

So much for arrays allocated in contiguous memory. Although there will be few occasions where 240 bytes cannot be allocated easily in contiguous memory, imagine a larger array of integers, say [128][256][512], which is 226 bytes or 64MB. On a 32-bit system, 64MB of contiguous RAM may not be available, so we must split the array into smaller arrays. This is where imagining multi-dimensional arrays as being one-dimensional arrays of one-dimensional arrays comes in handy. If we treat the first two dimensions as a two-dimensional array of integer pointers (each of which is 32-bits), then we only need 128*256*4 bytes, which is only 131,072 bytes or 128kB. Each pointer will reference a separate one-dimensional array of 512 integers, each of which is only 2kB in size (512*4). Although total memory consumption is now 256MB, because the allocation is split into one 128kB allocation and 512 separate 2kB allocations there's a far greater chance the allocation will succeed than if we attempt to allocate 64MB contiguously.

The index notation hasn't actually changed but the underlying pointer arithmetic has. If we assume the pointer array is p[128][256], then referencing p[64][128][256] will return the 257th element of the array pointed to by p[64][128]. This works because the first two dimensions return a pointer to a one-dimensional array of integers. If we suppose that the pointer is x, then the final dimension returns the integer stored at x[256].

The underlying arithmetic is a little cumbersome, but can be broken down as x = (p+(64*(256*4))+(128*4)) + (256*4), which reduces to x = (p+66048) + 1024. Thus the memory address stored at offset 66048 bytes within the pointer array plus the offset 1024 returns the 257th element of the appropriate one-dimensional array of integers.

How do you copy c program to msword?

If you want to copy C source code to a new file in MS Word, use the following steps:

  1. Open the C program in Notepad if it's not already open.
  2. Select all text (usually CTRL+A works fine).
  3. Copy that text to the clipboard (CTRL+C).
  4. Open MS Word (or Wordpad).
  5. CTRL+V to paste the C source code.
  6. Save if desired.

If the C source code is in a file, and you have Windows Explorer open with that file showing, you can open MS Word, and then drag the file from Explorer to MS Word, which will open that file.

Why you need to declare variable 1st in turbo c plus plus?

In C++ all names (including variables) must be declared before they can be used.

Why you use void res in c programming?

since, the word 'void' in C programming language means that it does not return any value to the user or calling function....this is usually used to specify a type of function...... for this reason w use 'void'in c program..

Is it possible to create a program to vote automatically and repeatedly in an on line contest?

Of course. It would be no problem at all for the average college student studying information technology. Of course it would be unethical, but that is your problem.

Write a standard lock plus double check to create a critical section around a variable access?

using System; using System.Text; using System.Threading; namespace thread01 { public class Counter { private int _count=0; private int _even=0; public int Count { get { return _count; } } public int EvenCount { get { return _even; } } private Object theLock = new Object(); public void UpdateCount() { lock (theLock) { _count = _count + 1; if (Count % 2 == 0) // An even number { _even += 1; } } } } class Program { static void Main(string[] args) { Counter count = new Counter(); ParameterizedThreadStart starter = new ParameterizedThreadStart(Program.UpdateCount); Thread[] threads = new Thread[10]; for (int x = 0; x < 10; ++x) { threads[x] = new Thread(starter); threads[x].Start(count); } for (int y = 0; y < 10; ++y) { threads[y].Join(); } Console.WriteLine("Total: {0} - Even: {1}", count.Count,count.EvenCount); Console.ReadKey(); Console.ReadKey(); } static void UpdateCount(object param) { Counter count = (Counter)param; for (int z = 1; z