#union_solution#
Solution
#include <stdio.h>
union hiddenMessage {
int ints[6];
char chars[21];
};
int main() {
union hiddenMessage intCharacters = {{1853169737, 1936876900, 1684955508, 1768838432, 561213039, 0}};
printf("[");
// only go to 18 because 1 byte is for the terminating 0 and we don't print the last in the loop
for(int i = 0; i < 19; ++i)
printf("%c, ", intCharacters.chars[i]);
printf("%c]\n", intCharacters.chars[19]);
printf("%s\n", intCharacters.chars);
}
C for beginners
Saturday, 16 February 2019
Union exercice
#union_exercice#
Solution
Exercise
Create a union that stores an array of 21 characters and 6 ints (6 since 21 / 4 == 5, but 5 * 4 == 20 so you need 1 more for the purpose of this exercise), you will set the integers to 6 given values and then print out the character array both as a series of chars and as a string.Solution
Unions
#unions#
C Unions are essentially the same as C Structures, except that instead of containing multiple variables each with their own memory a Union allows for multiple names to the same variable. These names can treat the memory as different types (and the size of the union will be the size of the largest type, + any padding the compiler might decide to give it)
So if you wanted to be able to read a variable's memory in different ways, for example read an integer one byte at a time, you could have something like this:
C Unions are essentially the same as C Structures, except that instead of containing multiple variables each with their own memory a Union allows for multiple names to the same variable. These names can treat the memory as different types (and the size of the union will be the size of the largest type, + any padding the compiler might decide to give it)
So if you wanted to be able to read a variable's memory in different ways, for example read an integer one byte at a time, you could have something like this:
union intParts {
int theInt;
char bytes[sizeof(int)];
};
Allowing you to look at each byte individually without casting a pointer and using pointer arithmetic:
union intParts parts;
parts.theInt = 5968145; // arbitrary number > 255 (1 byte)
printf("The int is %i\nThe bytes are [%i, %i, %i, %i]\n",
parts.theInt, parts.bytes[0], parts.bytes[1], parts.bytes[2], parts.bytes[3]);
// vs
int theInt = parts.theInt;
printf("The int is %i\nThe bytes are [%i, %i, %i, %i]\n",
theInt, *((char*)&theInt+0), *((char*)&theInt+1), *((char*)&theInt+2), *((char*)&theInt+3));
// or with array syntax which can be a tiny bit nicer sometimes
printf("The int is %i\nThe bytes are [%i, %i, %i, %i]\n",
theInt, ((char*)&theInt)[0], ((char*)&theInt)[1], ((char*)&theInt)[2], ((char*)&theInt)[3]);
Combining this with a structure allows you to
create a "tagged" union which can be used to store multiple different
types, one at a time.
For example, you might have a "number" struct, but you don't want to use something like this:
struct operator {
int intNum;
float floatNum;
int type;
double doubleNum;
};
How to create an abstract data type
#data_type#
1 – Define the abstract data type
The ADT in C is usually defined as a pointer to a structure. A header file contains the ADT declaration without any of the underlying details, leaving it up to the implementer to fully declare the ADT in the source module. Examples of ADTs include a StackPtr_t, NodePtr_t or QueuePtr_t to name a few. The example below shows how a developer might declare an ADT:
2 – Define the operations that can be performed on the data The operations that may be performed on an ADT completely depend on the ADT's purpose. For example, an ADT for a stack might include operations such as initialization, pushing data, popping data, destroying the stack, checking to see if the stack is full, checking to see if the stack is empty, and so on. Keep in mind that using an ADT is quite different from the way in which a developer would normally manipulate data.
3 – Fill in the interface specification The interface specification is the function prototype for all of the public operations that can be performed on the ADT. The interface specification should be located in the ADT header file. Going back to the stack example
Create the implementation The ADT's implementation could change from one application to the next. In fact, the ADT implementation could change during project development. That is one of the nice aspects of using an ADT: the implementation details are located in the source module and “hidden” from view of the higher level application developer. The use of an ADT thus provides a developer with a high degree of flexibility
Put the abstract data type to the test Finally, once a developer has specified and implemented an ADT it is time to put it to the test by writing some application code. The application code should declare an ADT and then manipulate the data's contents through by using the interface specification
1 – Define the abstract data type
The ADT in C is usually defined as a pointer to a structure. A header file contains the ADT declaration without any of the underlying details, leaving it up to the implementer to fully declare the ADT in the source module. Examples of ADTs include a StackPtr_t, NodePtr_t or QueuePtr_t to name a few. The example below shows how a developer might declare an ADT:
- typedef struct StackStruct_t * StackPtr_t;
2 – Define the operations that can be performed on the data The operations that may be performed on an ADT completely depend on the ADT's purpose. For example, an ADT for a stack might include operations such as initialization, pushing data, popping data, destroying the stack, checking to see if the stack is full, checking to see if the stack is empty, and so on. Keep in mind that using an ADT is quite different from the way in which a developer would normally manipulate data.
3 – Fill in the interface specification The interface specification is the function prototype for all of the public operations that can be performed on the ADT. The interface specification should be located in the ADT header file. Going back to the stack example
Create the implementation The ADT's implementation could change from one application to the next. In fact, the ADT implementation could change during project development. That is one of the nice aspects of using an ADT: the implementation details are located in the source module and “hidden” from view of the higher level application developer. The use of an ADT thus provides a developer with a high degree of flexibility
Put the abstract data type to the test Finally, once a developer has specified and implemented an ADT it is time to put it to the test by writing some application code. The application code should declare an ADT and then manipulate the data's contents through by using the interface specification
Thursday, 14 February 2019
Example4: Structures
#structures4#
Add Two Complex Numbers
#include <stdio.h>
typedef struct complex
{
float real;
float imag;
} complex;
complex add(complex n1,complex n2);
int main()
{
complex n1, n2, temp;
printf("For 1st complex number \n");
printf("Enter real and imaginary part respectively:\n");
scanf("%f %f", &n1.real, &n1.imag);
printf("\nFor 2nd complex number \n");
printf("Enter real and imaginary part respectively:\n");
scanf("%f %f", &n2.real, &n2.imag);
temp = add(n1, n2);
printf("Sum = %.1f + %.1fi", temp.real, temp.imag);
return 0;
}
complex add(complex n1, complex n2)
{
complex temp;
temp.real = n1.real + n2.real;
temp.imag = n1.imag + n2.imag;
return(temp);
}
OUTPUT
For 1st complex number Enter real and imaginary part respectively: 2.3 4.5 For 2nd complex number Enter real and imaginary part respectively: 3.4 5 Sum = 5.7 + 9.5i
Example3: Structures
#structures3#
Add two distances in inch-feet system
#include <stdio.h>
struct Distance
{
int feet;
float inch;
} d1, d2, sumOfDistances;
int main()
{
printf("Enter information for 1st distance\n");
printf("Enter feet: ");
scanf("%d", &d1.feet);
printf("Enter inch: ");
scanf("%f", &d1.inch);
printf("\nEnter information for 2nd distance\n");
printf("Enter feet: ");
scanf("%d", &d2.feet);
printf("Enter inch: ");
scanf("%f", &d2.inch);
sumOfDistances.feet = d1.feet+d2.feet;
sumOfDistances.inch = d1.inch+d2.inch;
// If inch is greater than 12, changing it to feet.
if (sumOfDistances.inch>12.0)
{
sumOfDistances.inch = sumOfDistances.inch-12.0;
++sumOfDistances.feet;
}
printf("\nSum of distances = %d\'-%.1f\"",sumOfDistances.feet, sumOfDistances.inch);
return 0;
}
OUTPUT
Enter information for 1st distance
Enter feet: 23
Enter inch: 8.6
Enter information for 2nd distance
Enter feet: 34
Enter inch: 2.4
Sum of distances = 57'-11.0"
Examples2: Structures
#structures#
Store Information and Display it Using Structure
#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
} s;
int main()
{
printf("Enter information:\n");
printf("Enter name: ");
scanf("%s", s.name);
printf("Enter roll number: ");
scanf("%d", &s.roll);
printf("Enter marks: ");
scanf("%f", &s.marks);
printf("Displaying Information:\n");
printf("Name: ");
puts(s.name);
printf("Roll number: %d\n",s.roll);
printf("Marks: %.1f\n", s.marks);
return 0;
}
OUTPUT
Enter information:
Enter name: Jack
Enter roll number: 23
Enter marks: 34.5
Displaying Information:
Name: Jack
Roll number: 23
Marks: 34.5
Wednesday, 6 February 2019
Example: C structure
#tutorial21#
Example: C structure
Example: C structure
Program to add two distances which is in feet and inches
#include <stdio.h>
struct Distance
{
int feet;
float inch;
} dist1, dist2, sum;
int main()
{
printf("1st distance\n");
printf("Enter feet: ");
scanf("%d", &dist1.feet);
printf("Enter inch: ");
scanf("%f", &dist1.inch);
printf("2nd distance\n");
printf("Enter feet: ");
scanf("%d", &dist2.feet);
printf("Enter inch: ");
scanf("%f", &dist2.inch);
// adding feet
sum.feet = dist1.feet + dist2.feet;
// adding inches
sum.inch = dist1.inch + dist2.inch;
// changing feet if inch is greater than 12
while (sum.inch >= 12)
{
++sum.feet;
sum.inch = sum.inch - 12;
}
printf("Sum of distances = %d\'-%.1f\"", sum.feet, sum.inch);
return 0;
}
Output1st distance Enter feet: 12 Enter inch: 7.9 2nd distance Enter feet: 2 Enter inch: 9.8 Sum of distances = 15'-5.7"
Keyword typedef
Keyword typedef can be used to simplify syntax of a structure.struct Distance{
int feet;
float inch;
};
int main() {
structure Distance d1, d2;
}
is equivalent totypedef struct Distance{
int feet;
float inch;
} distances;
int main() {
distances dist1, dist2, sum;
}
C Programming Structure
#tutorial20#
Here is an example:
Here's how we create structure variables:
How to define a structure?
Keywordstruct
is used for creating a structure.Syntax of structure
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeber;
};
Here is an example:
struct Person
{
char name[50];
int citNo;
float salary;
};
Create structure variable
When a structure is defined, it creates a user-defined type. However, no storage or memory is allocated. To allocate memory of a given structure type and work with it, we need to create variables.Here's how we create structure variables:
struct Person
{
char name[50];
int citNo;
float salary;
};
int main()
{
struct Person person1, person2, p[20];
return 0;
}
Another way of creating a structure variable is:
struct Person
{
char name[50];
int citNo;
float salary;
} person1, person2, p[20];
In both cases, two variables person1, person2, and an array variable p having 20 elements of type struct Person are created.How to Access members of a structure?
There are two types of operators used for accessing members of a structure.- Member operator(.)
- Structure pointer operator(->) (will be discussed in structure and pointers)
person2.salary
Monday, 4 February 2019
C exercices
#exercices1#
1) Write a C program to print a block F using hash (#), where the F has a height of six characters and width of five and four characters.
Expected Output:
1) Write a C program to print a block F using hash (#), where the F has a height of six characters and width of five and four characters.
Expected Output:
######
#
#
#####
#
#
#
2) Write a C program to print a big 'C'.
Expected Output:
######
## ##
#
#
#
#
#
## ##
######
Solutions
1)
int main()
{
printf("######\n");
printf("#\n");
printf("#\n");
printf("#####\n");
printf("#\n");
printf("#\n");
printf("#\n");
return(0);
}
2)
#include <stdio.h>
int main()
{
printf(" ######\n");
printf(" ## ##\n");
printf(" #\n");
printf(" #\n");
printf(" #\n");
printf(" #\n");
printf(" #\n");
printf(" ## ##\n");
printf(" ######\n");
return(0);
}
Saturday, 2 February 2019
Pointers Examples
#tutorial19#
If you have a variable var in your program,
You must have seen this notation while using
data_type* pointer_variable_name; int* p;
Address in C
Before you get into the concept of pointers, let's first get familiar with address in C.If you have a variable var in your program,
&var
will give you its address in the memory, where &
is commonly called the reference operator.You must have seen this notation while using
scanf()
function. It was used in the function to store the user inputted value in the address of var.scanf("%d", &var);
#include <stdio.h>
int main()
{
int var = 5;
printf("Value: %d\n", var);
printf("Address: %u", &var); //Notice, the ampersand(&) before var.
return 0;
}
Output
Value: 5
Address: 2686778
How to create a pointer variable?data_type* pointer_variable_name; int* p;
How Pointer Works?
#include <stdio.h>
int main()
{
int* pc, c;
c = 22;
printf("Address of c: %u\n", &c);
printf("Value of c: %d\n\n", c);
pc = &c;
printf("Address of pointer pc: %u\n", pc);
printf("Content of pointer pc: %d\n\n", *pc);
c = 11;
printf("Address of pointer pc: %u\n", pc);
printf("Content of pointer pc: %d\n\n", *pc);
*pc = 2;
printf("Address of c: %u\n", &c);
printf("Value of c: %d\n\n", c);
return 0;
}
Explanation of the programint* pc, c;
Here, a pointer pc and a normal variable c, both of typeint
, is created.
Since pc and c are not initialized at first, pointer pc points to either no address or a random address. And, variable c has an address but contains a random garbage value.
c = 22;
This assigns 22 to the variable c, i.e., 22 is stored in the memory location of variable c.
Note that, when printing&c
(address of c), we use%u
rather than%d
since address is usually expressed as an unsigned integer (always positive).
pc = &c;
This assigns the address of variable c to the pointer pc.
You see the value of pc is same as the address of c and the content of pc is 22 as well.
c = 11;
This assigns 11 to variable c.
Since, pointer pc points to the same address as c, value pointed by pointer pc is 11 as well.
*pc = 2;
This change the value at the memory location pointed by pointer pc to 2.
Since the address of the pointer pc is same as the address of c, value of c is also changed to 2.
Wednesday, 30 January 2019
Monday, 28 January 2019
c examples 3
#tutorial18#
Loop examples
Enter an integer: 5
Factorial = 120
Loop examples
// Program to find factorial of a number
// For a positive integer n, factorial = 1*2*3...n
#include <stdio.h>
int main()
{
int number;
long long factorial;
printf("Enter an integer: ");
scanf("%d",&number);
factorial = 1;
// loop terminates when number is less than or equal to 0
while (number > 0)
{
factorial *= number; // factorial = factorial*number;
--number;
}
printf("Factorial= %lld", factorial);
return 0;
}
OutputEnter an integer: 5
Factorial = 120
Subscribe to:
Posts (Atom)