C
Problem 01
“Hello World!” in C
This challenges requires you to print Hello, World!
on a single line, and then print the already provided input string to stdout.
Example: s = "Life is beautiful"
Output
Hello, World!
Life is beautiful
Solution
#include <stdio.h>
int main() {
char s[100];
("%[^\n]%*c", &s);
scanf("Hello, World!\n");
printf("%s",s);
printfreturn 0;
}
Problem 02
Playing with Characters
You have to print the character ch
, in the first line. Then print s
in next line. In the last line print the sentence sen
.
Input format - take a character, ch
as input - take the string, s
as input - take the sentence sen
as input
Example
C
Language
Welcome To C!!
Solution
#include <stdio.h>
int main()
{
char ch;
char s[100];
char sen[100];
("%c",&ch);
scanf("%s",&s);
scanf();
getchar("%[^\n]%*c", sen);
scanf
("%c\n",ch);
printf("%s\n",s);
printf("%s\n",sen);
printfreturn 0;
}
Problem 03
Sum and Difference of Two Numbers
Your task is to take two numbers of int
data type, two numbers of float
data type as input and output their sum:
- Declare 4 variables: two of type
int
and two of typefloat
- Read 2 lines of input stdin and initialize your 4 variables
- Use the + and - operator to perfom the following operations:
- Print the sum and difference of two
int
variable on a new line. - Print the sum and difference of two
float
variable rounded to one decimal place on a new line.
- Print the sum and difference of two
Solution
int main()
{
int a;
int b;
float c;
float d;
("%d", &a);
scanf("%d", &b);
scanf("%f", &c);
scanf("%f", &d);
scanf
("%d %d\n" , a+b, a-b);
printf("%.1f %.1f\n" , c+d, c-d);
printfreturn 0;
}
Problem 04
Functions in C
Write a function:
int max_of_four(int a, int b, int c, int d)
which reads four arguments and returns the greatest of them
Solution
int max_of_four(int a, int b, int c, int d) {
int max = 0;
int list[4] = {a, b, c, d};
for(int i=0; i<4; i++) {
if(max < list[i]) {
= list[i];
max }
}
return max;
}
int main() {
int a, b, c, d;
("%d %d %d %d", &a, &b, &c, &d);
scanfint ans = max_of_four(a, b, c, d);
("%d", ans);
printfreturn 0;
}
Problem 05
Pointers in C
Complete the function:
void update(int *a, int *b)
It receives two integer pointers, int *a
and int *b
. Set the value of a
to their sum, and b
to their absolute difference. There is no return value, and no return statement is needed
- \(a' = a +b\)
- \(b' = |a - b|\)
Solution
#include <stdio.h>
void update(int *a,int *b) {
int sum;
int dif;
= *a + *b;
sum = *a - *b;
dif if(dif < 0) {
= -dif;
dif }
*a = sum;
*b = dif;
}
int main() {
int a, b;
int *pa = &a, *pb = &b;
("%d %d", &a, &b);
scanf(pa, pb);
update("%d\n%d", a, b);
printfreturn 0;
}