1. Write a C program that prints out a char array, an int, and a float using pri
ID: 3688536 • Letter: 1
Question
1. Write a C program that prints out a char array, an int, and a float using printf.
2. Write a C program that creates two arrays of integers, one on the stack and one on the heap. You will loop through these arrays and populate them with values (any value is fine). You will then loop through these arrays again and print each value. Your output should look something like “Value in index 1 is 100 from stack array and 100 from heap array.” Do not forget to print newlines. Do not forget to de-allocate any memory you allocate.
3. Write a program that allocates an array on the heap and then iterates through the heap using pointer arithmetic. Print the item as in part 2 at each iteration. Loop backwards through the array using pointer arithmetic and print as well.
4. Write a program that computes the fibonnaci sequence using recursion by calling its own function. Output the first 20 numbers of the sequence.
Explanation / Answer
1. Write a C program that prints out a char array, an int, and a float using printf.
Initialization of Array in C programming language.
In C programming language an array is not initialized automatically at the time of declaration. By default, array elements contain garbage value. Like any other variable in C, we can initialize arrays at the time of declaration.
Array Initialization by Specifying Array Size int score[7] = {5,2,9,1,1,4,7};
Initialization of array after declaration. int score[7];
score[0] = 5;
score[1] = 2;
score[2] = 9;
score[3] = 1;
score[4] = 1;
score[5] = 4;
score[6] = 7;
Array Initialization Without Specifying Array Size int score[] = {5,2,9,1,1,4,7}
In above declaration, compiler counts the number of elements inside curly braces {} and determines the size of array score. Then, compiler will create an array of size 7 and initialize it with value provided between curly braces {} as discussed above.
String in C programming language is a one-dimensional array of characters which is terminated by a null character (''). A character array which is not null terminated is not a valid C string. In a C string, each character occupies one byte of memory including null character.
Null character marks the end of the string; it is the only way for the compiler to know where this string is ending. Strings are useful when we are dealing with text like Name of a person, address, error messages etc.
Examples of C Strings
Points to Remember about Strings in C
For Example
String constant: "SampleCharacter"
Character constant: 'S'
Syntax of String Declaration
char string_name[SIZE_OF_STRING];
-------------------------------------------------------------------------------------------------------------------
C Program
#include <stdio.h>
#include <conio.h>
int main(){
/* Integer array initialization by specifying array size */
int roll[7] = {1,2,3,4,5,6,7};
/*floating array initialization by without specifying array size */
double marks[] = {50.1,71.00,67.13,56.10,89.50,40.7,97.1};
/*character array initialization by specifying array size */
char name[16] = "abcdefg";
int i;
/* Printing array elements using loop */
printf("Roll_Number Name Marks ");
for(i = 0; i < 7; i++){
printf("%5d %9c %9f ", roll[i], name[i],marks[i]);
}
getch();
return 0;
}
Output
Roll_Number Name Marks
1 a 50.1
2 b 71.00
3 c 67.13
4 d 56.10
5 e 89.50
6 f 40.7
7 g 97.1
---------------------------------------------------------------------------------------------------------------------------------------------------
2. Write a C program that creates two arrays of integers, one on the stack and one on the heap. You will loop through these arrays and populate them with values (any value is fine). You will then loop through these arrays again and print each value. Your output should look something like “Value in index 1 is 100 from stack array and 100 from heap array.” Do not forget to print newlines. Do not forget to de-allocate any memory you allocate.
The Stack
What is the stack? It's a special region of your computer's memory that stores temporary variables created by each function (including the main () function). The stack is a "LIFO" (last in, first out) data structure, which is managed and optimized by the CPU quite closely. Every time a function declares a new variable, it is "pushed" onto the stack. Then every time a function exits, all of the variables pushed onto the stack by that function, are freed (that is to say, they are deleted). Once a stack variable is freed, that region of memory becomes available for other stack variables.
The advantage of using the stack to store variables, is that memory is managed for you. You don't have to allocate memory by hand, or free it once you don't need it any more. What's more, because the CPU organizes stack memory so efficiently, reading from and writing to stack variables is very fast.
A key to understanding the stack is the notion that when a function exits, all of its variables are popped off of the stack (and hence lost forever). Thus stack variables are local in nature. This is related to a concept we saw earlier known as variable scope, or local vs global variables. A common bug in C programming is attempting to access a variable that was created on the stack inside some function, from a place in your program outside of that function (i.e. after that function has exited).
Another feature of the stack to keep in mind, is that there is a limit (varies with OS) on the size of variables that can be store on the stack. This is not the case for variables allocated on the heap.
To summarize the stack:
The Heap
The heap is a region of your computer's memory that is not managed automatically for you, and is not as tightly managed by the CPU. It is a more free-floating region of memory (and is larger). To allocate memory on the heap, you must use malloc() or calloc(), which are built-in C functions. Once you have allocated memory on the heap, you are responsible for using free () to deallocate that memory once you don't need it any more. If you fail to do this, your program will have what is known as a memory leak. That is, memory on the heap will still be set aside (and won't be available to other processes). As we will see in the debugging section, there is a tool called valgrind that can help you detect memory leaks.
Unlike the stack, the heap does not have size restrictions on variable size (apart from the obvious physical limitations of your computer). Heap memory is slightly slower to be read from and written to, because one has to use pointers to access memory on the heap. We will talk about pointers shortly.
Unlike the stack, variables created on the heap are accessible by any function, anywhere in your program. Heap variables are essentially global in scope.
Stack vs Heap Pros and Cons
Stack
Heap
/* C Program */
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
int i;
int srno[3]={1,2,3};
int *age = malloc(sizeof(int));
*age = 30;
int *salary = malloc(sizeof(int));
*salary = 12345;
int *myList = malloc(3 * sizeof(int));
myList[0] = 12;
myList[1] = 23;
myList[2] = 34;
/* Stack*/
For(i=0;i<3;i++)
Printf(“serial no on stack is %d”,srno[i]);
int *twiceSalary = multiplyByTwo(salary);
printf(" salary is on heap is %.3f ", *twiceSalary);
free(age);
free(salary);
free(myList);
free(twiceSalary);
return 0;
}
int *multiplyByTwo (int *input) {
int *twice = malloc(sizeof(int));
*twice = *input * 2.0;
return twice;
}
---------------------------------------------------------------------------------------------------------------------------------------------------
3. Write a program that allocates an array on the heap and then iterates through the heap using pointer arithmetic. Print the item as in part 2 at each iteration. Loop backwards through the array using pointer arithmetic and print as well.
---------------------------------------------------------------------------------------------------------------------------------------------------
4. Write a program that computes the Fibonacci sequence using recursion by calling its own function. Output the first 20 numbers of the sequence.
Fibonacci series are the numbers in the following integer sequence
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89....
the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent term is the sum of the previous two terms. In mathematical terms, the nth term of Fibonacci numbers is defined by the recurrence relation:
Below program uses recursion to calculate Nth fibonacci number. To calculate Nth fibonacci number it first calculate (N-1)th and (N-2)th fibonacci number and then add both to get Nth fibonacci number.
For Example : fibonacci(4) = fibonacci(3) + fibonacci(2);
C program to print fibonacci series till Nth term using recursion
In below program, we first take the number of terms of fibonacci series as input from user using scanf function. We are using a user defined recursive function named 'fibonacci' which takes an integer (N) as input and returns the nth fibonacci number using recursion as discussed above. The recursion will terminate when number of terms are < 2 because we know the first two terms of fibonacci series are 0 and 1.
In line number 17, we are calling this function inside a for loop to get the Nth term of series.
/*
* C Program to print Fibonacci series using recursion
*/
#include <stdio.h>
#include <conio.h>
int fibonacci(int term);
int main(){
int terms, counter;
printf("Enter number of terms in Fibonacci series: ");
scanf("%d", &terms);
/*
* Nth term = (N-1)th therm + (N-2)th term;
*/
printf("Fibonacci series till %d terms ", terms);
for(counter = 0; counter < terms; counter++)
{
printf("%d ", fibonacci(counter));
}
getch();
return 0;
}
/*
* Function to calculate Nth Fibonacci number
* fibonacci(N) = fibonacci(N - 1) + fibonacci(N - 2);
*/
int fibonacci(int term){
/* Exit condition of recursion*/
if(term < 2)
return term;
return fibonacci(term - 1) + fibonacci(term - 2);
}
Program Output
Enter number of terms in Fibonacci series: 20
Fibonacci series till 20 terms
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.