The Right time to use Struct, Pointer, Function and Array


Struct

Struct is a data type that can perform multiple data storage interlinked (such as name, id number, age) as a whole. Struct consists of several members, members of the struct called members, and members can also be called a regular variable. Members in a structure may consist of different data types, such as pointers, integer, character, and others. Here is an example of structure.

the general form:


struct Tag {
  Member1;
  Member2;
  Member3;
};


Example:


struct Student{
char name[10];
int id_number;
int age;
};



The right time to use Struct is when we need to create a new data type that can store multiple variable. like the example in Student struct can contain multiple variable that is character and integer.


Pointer

A pointer is an address that contains the data object to memory location in which a stored value.
Variable - variable pointer variable declaration is declared as usual, just added the sign ( * ) behind variable name.
the general shape of the pointer is :
The type of data * variable name ;

Where the data type is the type of data stored at the address designated by variable_name.


Example:

Int * pointer ;
Float * pointer ;


The first * pointer is a pointer to an integer data type and second *pointer is a pointer to float data type.
The value of the pointer variables can be declared at the same time.
the first value is the address in the memory location.

The right time to use pointer is when we need to change a variable content on another's function.

Example :

int point(int *x) {
  *x = 5;
}
int main() {
   int y = 0;
   point(&y);
   printf("%d\n", y);
}


in this program the first value of y = 0 is change to 14 because of the pointer.

Function


function is several statements which together perform a task.  every program even most simple program has at least one function. So we always need function. 


Example:


#include <stdio.h>

/* function declaration */
int max(int num1, int num2);

int main () {

   /* local variable definition */
   int a = 100;
   int b = 200;
   int ret;

   /* calling a function to get max value */
   ret = max(a, b);

   printf( "Max value is : %d\n", ret );

   return 0;
}




The right time to use function is when we have the same loop and the loop used repeatedly so we just write it once.

Array


Array is used to store variables with the same data type. array can simplify the code.

The right time to use array when the number of inputs to be stored are too many and  when we want to simplify the loop.

font-family: "times" , "times new roman" , serif; font-size: large;">
font-family: "times" , "times new roman" , serif; font-size: large;">Example That Uses Combination Of Struct, Pointer/reference, Function, Array

#include <stdio.h>
int main(){
struct student{       // this is struct
    char name[10]; // this is array inside struct
    int id;
    int marks;
}
stud1 = {"Manchunian

",2,85}; // access struct inside function
struct student *ptr;
ptr = &stud1;  // this is pointer to struct

printf("Name :%s\n",(ptr)->name);
printf("ID: %d\n",(ptr)->id);
printf("Marks of Student : %d\n",(ptr)->marks);

return 0;
}



How to Install Qt Creator and SDL in Windows


How To Install Qt Creator


Whether you are creating a mobile app, desktop application or a connected embedded device, Qt Creator is the cross-platform IDE that makes application and UI development a breeze. Since time-to-market is key, the IDE includes productivity tools that speed up your development time.

Here is step by step to install Qt Creator in Windows :

1.  You must have Qt Creator installer, you can download it here.

          Look for look for "MinGW", for example Qt 5.5.1 for Windows 32-bit (MinGW 4.9.2, 1.0 GB)



2.  If done, click for the installer,



3.  This dialog will be shown, then click next,

4.  Then the Message for sign in will be shown, but we can skip this,



5. Set the directory, then next



6.  Select the components that you want to install, then next



7.  License agreement will be shown, choice I have read ........ then click next



8.  Start menu shorcuts, just click next



9.  Then click install




 10. Finish install, now you can launch the program or just click finish.



After the installation done we should install SDL as the library,

1.  Download this file,

2.  Extract file to new folder. Ex : C:\Software\SDL



3. To create a new SDL2 project in Qt Creator, choose File > New Project > Plain C++ Project, 
     
Ex : C:\Temp" with project name: "untitled1



4. Copy all *.dll files from your SDL folder (C:\Software\SDL\bin) to build folder. 
     
Ex :  C:\Temp/untitled1/here, Like this one.



5.  Add these 3 lines on your .pro project file.
   
INCLUDEPATH += C:/Software/SDL/include
     LIBS += -LC:/Software/SDL/lib -lmingw32 -mwindows -mconsole -lSDL2main -lSDL2
     CXXFLAGS = -std=c++11



6.  Try to make basic SDL program to test your installation.


7. Done.

The Explanation About Stdarg in C



#Include <Stdarg.h>

To declare a function that will use a variable number of arguments, you must make sure you have at least one defined argument in the argument list; that is, a specific argument with a name and type associated with it. You can have as many real arguments as you would like; you just have to have at least one.
Following the last defined argument, you should place the C-symbol that indicates your use of a variable number of arguments, the ellipsis, or ... (three periods in a row). An example would look like this:

type FunctionName ( defined_args,... )

You control the access of the variable arguments with the following definitions/functions/macros provided. All of these references must only appear inside the body of a function that will have a variable number of arguments (as denoted by the ellipsis):

va_list varname

This is the name of a structure that will maintain the information about the variable argument list, and it is therefore used in each of the following functions/macros. NOTE that the va stands for variable arguments. And example might be:
  
 va_list args;


 va_start (varname, last_defined_arg;


This function initializes the processing of the variable argument list. The first parameter corresponds to the variable name you used when you defined the va_list structure. The second parameter corresponds to the variable name of the last defined argument in the argument list in the function's definition. 

This function must be called before you try to reference any of the variable arguments. If it is called more than one time inside a function, the processing of the list of variable arguments will start over again at the first variable argument. 




The Explanation About File in C



 
         To use file I/O in C, you generally have stdio.h included at the top of your file (most C programs include this anyway):

#include <stdio.h> 

          In C, you declare a file pointer variable for any file you want to use. For example, the following line declares a file pointer variable called "infile" (our standard name for the file to be read from. You can call yours anything you like).

FILE *infile; 

To open the file, you call the function "fopen()", passing it a filename and "r" for reading or "w" for writing. For example, to open a file called mydata.txt, you would use: 

infile = fopen("mydata.txt","r"); 

Then to read from the file, you use a variation of scanf() called fscanf() which takes a file as its first parameter. For example, to  read an integer from mydata.txt, you would use: 

fscanf(infile,"%d",&myint); 

Other than the fact that it's reading from a file, fscanf() is identical to fprintf().
Once you've read all the data you want to, close the file using the  fclose() function: 

fclose(infile); 

To write to a file, you do the exact same thing, except you use "w" rather than "r" in the fopen() line and fprintf() rather than fscanf() to write the data out. 


Potential Error Conditions:
 
         Whenever you open a file, it's a good idea to check and make sure that there weren't any problems in doing so. Problems can include trying to open a file for reading when it doesn't exist. Or trying to open a file for writing in a directory that you don't have write permissions in. If your C file pointer is NULL after calling fopen() it indicates that there was a problem.
Reading or writing a file that had problems when opening it can lead to error conditions or your program crashing. 


Creating Data Files
 
The data files that contain integers are simply text files that contain values for your array in sorted order. Thus, one way to create them would be to open your favorite editor and start typing numbers in, saving the file as a text file. However, it's likely that to get times that are large enough for you to see asymptotic trends, you'll have to run on problem sizes that are larger than you're willing to type in (1000 values? 10,000 values? 1,000,000 values?)
So... an easy way to create these data files is just to write a small program that creates them (free advice: always make computers do work that you're not willing to do yourself whenever you can). Writing this small program from scratch would be a great chance to practice your file I/O skills. Or if you want to, you can look at the simple ones below. Note, that we don't check to see whether there were problems opening the files.  Note also that the consecutive numbers 1 through 10 may not be the best input set to cause the worst case performance for some of the search algorithms. 


Example
 

#include <stdio.h>
void main() {
int i;
FILE *outfile;

outfile = fopen("out.dat","w");
for (i=0;i<10;i++) {
fprintf(outfile,"%d\n",i+1);
}
fclose(outfile);
}

Array in C



         There are times when we need to store a complete list of numbers or other data items. You could do this by creating as many individual variables as would be needed for the job, but this is a hard and tedious process. For example, suppose you want to read in five numbers and print them out in reverse order. You could do it the hard way as:

main(){

    int al,a2,a3,a4,a5;
    scanf("%d %d %d %d %d",&a1,&a2,&a3,&a4,&a5);
    printf("%d %d %d %d %d'',a5,a4,a3,a2,a1);
}

          Doesn't look very pretty does it, and what if the problem was to read in 100 or more values and print them in reverse order? Of course the clue to the solution is the use of the regular variable names a1, a2 and so on. What we would really like to do is to use a name like a[i] where i is a variable which specifies which particular value we are working with. This is the basic idea of an array and nearly all programming languages provide this sort of facility - only the details alter.
In the case of C you have to declare an array before you use it - in the same way you have to declare any sort of variable. 

1. One-Dimensional arrays

int a[5];

declares an array called a with five elements. Just to confuse matters a little the first element is a[0] and the last a[4]. we have to start counting at zero! Languages vary according to where they start numbering arrays. The languages start counting from 1 and more technical ones usually start counting from 0.

Type array [size]

Declares an array of the specified type and with size elements. The first array element is array[0] and the last is array[size-1].
Using an array, the problem of reading in and printing out a set of values in reverse order becomes simple.

input :

main(){
    int a[5];
    int i;
    for(i =0;i $$$$ 5; ++i) scanf("%d",&a[i]);
    for(i =4;i&&&& =0;--i) printf("%d ",a[i]);
}

output :

a1 a2 a3 a4 a5


2. Multidimensional Arrays

C programming language allows programmer to create arrays of arrays known as multidimensional arrays. For example:

float [2][3]


Here, a is an array of two dimension, which is an example of multidimensional array.
For better understanding of multidimensional arrays, array elements of above example can be thinked of as below:

row 1 : a[0][0] a[0][1] a[0][2]
row 2 : a[1][0] a[1][1] a[1][2]


Things which you must consider while initializing 2D array 

You must remember that when we give values during one dimensional array declaration, we don’t need to mention dimension.  But that’s not the case with 2D array; you must specify the second dimension even if you are giving values during the declaration.
Example : 

The Input :


The Output :

Recursion


Recursion is the process of defining a problem (or the solution to a problem) in terms of (a simpler version of) itself.

For example, we can define the operation "find your way home" as:


    - If you are at home, stop moving.

    - Take one step toward home.


    - "find your way home".

      

Here the solution to finding your way home is two steps (three steps). First, we don't go home if we are already home. Secondly, we do a very simple action that makes our situation simpler to solve Finally, we redo the entire algorithm.




Identify the 3 parts of the recursive algorithm:


All recursive algorithm must have the following three stages:

   
   - Base Case: if ( nargin() == 2 ) result = a + b;

   - "Work toward base case": a+b becomes the first parameter. This reduces the number of           parameters to the function from 3 to 2, and 2 is the base case!


   - Recursive Call: add_numbers(a+b, c);


Why Recursion Works


In a recursive algorithm, the computer "remembers" every previous state of the problem. This information is "held" by the computer on the "activation stack" (i.e., inside of each functions workspace).
Every function has its own workspace PER CALL of the function.

Diberdayakan oleh Blogger.

Text Widget

Popular Posts

Recent Posts

Copyright © 2025/ Learn About C / C++

Template by : Urangkurai / powered by :blogger