/r/C_Homework
Come here if your C programming question is specifically related to a homework assignment.
We will not provide you with answers, but we will try our best to guide you in the direction you need.
The best resource is your classmates, professor, TAs, etc.
/r/C_Homework
I'm working on improving my C programming skills and have encountered a confusing aspect related to pointer declarations. I'm hoping to gain a better understanding of the differences between these two statements:
int *ptr[3];
int (*ptr)[3];
While they may appear similar at first glance, I believe there are significant differences in their meanings and implications. I would appreciate it if you could help me understand:
Hi.
We've been assigned a simple assignment it would seem, to sum all rows of an array with POSIX threads. We've been shown basic functions like pthread_create, _self, _join, _exit, _detach but not mutexes or semaphores.
I've come up with this: https://pastebin.com/ndhsVdJ0, but the results are different (and very wrong) each time this program is executed - for example the same row number gets written on stdout, and on top of that, sometimes the sum is a negative number. What am I doing wrong?
Thanks.
Our homework is to take n-amount of integer inputs from the user, see which ones are positive numbers and finally print how many of them were positive numbers. It seems like an easy task, however, I am new to C and don't quite know why this happens.
Every time I ask the user for input and store it, it doesn't get saved and returns -9560. Help on this would be much appreciated.
#include <stdio.h>
int main() {
int entry_limit, num;
int len = 0;
scanf("%d", &entry_limit);
for (int i = 1; i <= entry_limit; i++) {
scanf("%d", &num);
printf("entered: %d", &num);
/*if (num >= 0) {
len++;
}*/
}
printf("%d\n", &len);
return 0;
}
As you begin your Fall semester, choose a reliable and expert partner to walk with you through it successfully. I am a highly proficient tutor with over 7 years experience. I provide authentic help to authentic students genuinely in need of help and someone to talk to about their courses. My areas of specialization are engineering, math, physics, CAD, programming using Java, Python, Javascript, C++, et cetera and statistics. I'm timely, highly affordable and extremely confidential. With me, you can be assured of a top grade in every assignment and/or exam. Feel free to reach to me via email: helpmeprof001@gmail.com or check my profile for more info and reliable help in all fields of study.
Let's look back at some memorable moments and interesting insights from last year.
Your top 10 posts:
hello, the title may be confusing but I have a homework assignment due soon. In this assignment I was given a file, with value n. n represents how many x values there are going to.
How can i scan the value n, and create that amount of linked-list to later print.
Hi! I have a school assignment where I have to write a program in C and then test it, I will put the code below.
#include <stdio.h>
#include <stdlib.h>
#include "mylist.h"
#include <string.h>
struct student* create_list_element(char *name, float grade) {
struct student *element = (struct student *) malloc(sizeof(struct student));
strcpy(element->name, name);
element->grade = grade;
element->next = NULL;
return element;
}
void add_student(struct student* list, char* name, float grade) {
printf("REACHED ADD\n");
struct student *n = list;
while (n->next != NULL) {
n = n->next;
}
n->next = create_list_element(name, grade);
}
struct student* search_student(struct student* list, char* name) {
struct student *n = list;
do {
if (strcmp(n->name, name) == 0) {
return n;
}
n = n->next;
} while (n->next != NULL);
return NULL;
}
struct student *del_student(struct student* list, char* name) {
struct student *n = list;
struct student *m = list->next;
while (m->next != NULL) {
if (strcmp(n->name, name) == 0) {
printf("Name: %s\nGrade: %.1f", n->name, n->grade);
n->next = m->next;
free(n);
break;
}
n = m;
m = m->next;
}
}
void print_list(struct student* list) {
struct student *n = list;
do {
printf("Name: %s\nGrade: %.1f\n", n->name, n->grade);
n = n->next;
} while (n->next != NULL);
}
float compute_average(struct student* list) {
struct student *n = list;
float sum = 0.0;
int count = 0;
if (n != NULL) {
do {
sum += n->grade;
++count;
n = n->next;
} while (n->next != NULL);
}
return sum / count;
}
void free_list(struct student* list) {
struct student *n = list;
struct student *m = list->next;
do {
free(n);
n = m;
m = m->next;
} while (m->next != NULL);
}
and
#include <stdio.h>
#include <stdlib.h>
#include "mylist.h"
#include "mylist.c"
int main() {
int N;
printf("Number of students to be inserted: ");
scanf("%d", &N);
struct student *list;
printf("\nInsert %d students:\n", N);
for (int i = 0; i < N; ++i) {
char name[NAME_MAX];
float grade;
printf("\nName: ");
scanf("%s", &name);
printf("Grade: ");
scanf("%f", &grade);
printf("\n");
if (i == 0) {
list = create_list_element(name, grade);
} else {
add_student(list, name, grade);
}
}
char choice;
printf("Select one of the following commands:\n'c': search a student\n'e': delete a student\n'l': print list\n'q': exit program\n");
do {
printf("\n");
switch (choice) {
case 'c' : {
char name[NAME_MAX];
printf("Name: ");
scanf("%s", &name);
if (search_student(list, name) != NULL) {
printf("\nGrade: %.1f", search_student(list, name)->grade);
} else {
printf("\nERR: Search was unsuccessful.");
}
}
case 'e' : {
char name[NAME_MAX];
printf("Name: ");
scanf("%s", &name);
if (search_student(list, name) == NULL) {
printf("\nERR: Search was unsuccessful.");
} else {
del_student(list, name);
}
}
case 'l' : {
print_list(list);
}
case 'q' : {
print_list(list);
compute_average(list);
free_list(list);
}
}
} while (choice != 'q');
}
I know other parts might not be perfect, but right now when I run the program it asks me successfully the number of students I want to insert and it lets me insert the students one by one, but when I reach the last student and send, right when it should ask to select a command, it seems stuck in a infinite loop and the command line with it. It's one of my first times programming with C so I would be grateful for any type of help!
I cant adjust the following code of 2 dimensions Bezier to 3 dimensions Bezier. Any help will be much appreciated
#include <iostream> #include <fstream> #include <cmath> #include <vector> using namespace std; vector < vector <double> > bezm(25, vector <double> (25)); void paragon(int n, int i, int &k) { int ks = max(i,n-i)+1; int kp = min(i,n-i); k=1; for(int iii=ks;iii<=n;iii++) k = kiii; for(int iii=1;iii<=kp;iii++) k = k/iii; } void inibezier(int nco) { int kres1,kres2,kres3; for(int mi=0;mi<nco;mi++) { double b=0.e0; double c=0.e0; for(int i=0;i<nco;i++) { paragon(nco-1,i,kres1); paragon(i,mi,kres2); kres3=pow(-1,(i-mi)); double coeffi = double(kres1kres2kres3); if(mi>i) coeffi=0.e0; bezm[mi][i]=coeffi; } } } void usebezier( vector <double> xco, vector <double> yco, int nco, vector <double> &x , vector <double> &y , int ideg) { double aa1 = 0.5e0; double dd = 0.1e0; for(int k=0;k<=ideg+1;k++) y[k] = double(k-1)/double(ideg); for(int kpoi=0;kpoi<=ideg+1;kpoi++) { int kpoi1=kpoi;//+1; double tlocal = y[kpoi1]; x[kpoi1]=0.e0; y[kpoi1]=0.e0; for(int mi=0;mi<nco;mi++) { double b=0.e0; for(int i=0;i<nco;i++) b = b + bezm[mi][i]pow(tlocal,i); x[kpoi1] += bxco[mi]; y[kpoi1] += byco[mi]; } } } int main(int argc, char** argv) { string line; vector <double> val(1000,0); vector <double> x(1000,0); vector <double> y(1000,0); vector <double> xb( 25,0); vector <double> yb( 25,0); ifstream in("bezier.dat"); int nb=0; for(int i=0;i<26;i++) { in>>xb[i]>>yb[i]; getline(in,line); if(in.eof()) { nb = i; break; } } in.close(); inibezier(nb); int ideg; cout<<"Type the number of points along the final curve"<<endl; cin>>ideg; usebezier(xb,yb,nb,x,y,ideg-1); ofstream out("curve"); for(int i=1;i<ideg+1;i++) out<<"\t"<<x[i]<<"\t"<<y[i]<<endl; out.close(); }
I have to deliver a client-server academic project where you can access themed rooms and then be randomly connected to a user in that same room.
Is it possible that there are existing projects of this type? If so do you know where?
I state that the code that I attach and maybe the problem that I present, is quite long and may take some time for this I thank you from now for the time you are dedicating to me. 🎇You are an angel to me🎇.
I need to create a TCP server in C that accepts multiple clients who can choose a theme room in which you are randomly associated with a user (in the same room) and you can chat until one of them leaves, and then you are associated with the next user.
In about a month I managed with what little knowledge I had to create a server that, with 5 rooms, allows a user to choose one and wait for another user to choose the same room to chat. Each room has a maximum of 2 users and, if all 5 rooms were full, the other clients could not do anything.
I am tight on deadlines and have yet to implement the client in android. I'm here to ask for help on how to allow multiple clients to be associated in each topic room and from there then associate each pair of clients in a chat randomly.
server.c
//99 means, room is empty
//gcc server.c o server
//./server
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#define SIZE sizeof(struct sockaddr_in)
#define MAX 10
#define PORT_NO 3251
int client[MAX];
int ActiveClients = 0;
int msgcount[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
struct rooms
{
int roomid;
int person1;
int person2;
};
void findMax(int *maxfd)
{
int i;
*maxfd = client[0];
for (i = 1; i < MAX; i++)
if (client[i] > *maxfd)
*maxfd = client[i];
}
void logConnections(int type_con, char *IP_ADDR)
{
time_t rawtime;
struct tm *timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
FILE *fp = fopen("logs/connections.txt", "a+");
if (type_con == 1)
{
fprintf(fp, "Connected : %s - Connection time is : %s", IP_ADDR, asctime(timeinfo));
}
else
{
fprintf(fp, "Disconnected : %s - Disconnection time is : %s", IP_ADDR, asctime(timeinfo));
}
fclose(fp);
}
void logMessages(int clientid, int rec, char *msg, int roomid)
{
time_t rawtime;
struct tm *timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
char contitle[100];
contitle[0] = roomid;
FILE *fp = fopen("logs/conversations/chatlog.txt", "a+");
fprintf(fp, "Room : %d - Date: %s ,%d -> %d : Message Content : %s\n", roomid, asctime(timeinfo), clientid, rec, msg);
fclose(fp);
}
int main()
{
int sockfd, maxfd, nread, found, i, j, k;
char buf[128];
struct rooms room[6];
for (k = 0; k < 6; k++)
{
room[k].roomid = k;
room[k].person1 = 99;
room[k].person2 = 99;
}
fd_set fds;
struct sockaddr_in server = {AF_INET, PORT_NO, INADDR_ANY};
struct sockaddr_in their_addr; // connector's address information
int clientaddr = sizeof(their_addr);
//Messages
char rejectmessage[] = "Room is full\n";
char acceptmessage[] = "Connection accepted\n";
char roomerror[] = "We don't have a room like that\n";
char alonemsg[] = "You are alone in room\n";
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
printf("Error creating SOCKET\n");
return (0);
}
if (bind(sockfd, (struct sockaddr *)&server, SIZE) == -1)
{
printf("bind failed\n");
return (0);
}
if (listen(sockfd, 5) == -1)
{
printf("listen failed\n");
return (0);
}
else
{
puts("Server is running...\n");
}
findMax(&maxfd);
for (;;)
{
findMax(&maxfd);
maxfd = (maxfd > sockfd ? maxfd : sockfd) + 1;
FD_ZERO(&fds);
FD_SET(sockfd, &fds);
for (i = 0; i < MAX; i++)
if (client[i] != 0)
FD_SET(client[i], &fds);
/* Wait for some input or connection request. */
select(maxfd, &fds, (fd_set *)0, (fd_set *)0, (struct timeval *)0);
/*If one of the clients has some input, read and send it to related client.*/
for (i = 0; i < MAX; i++)
if (FD_ISSET(client[i], &fds))
{
nread = recv(client[i], buf, sizeof(buf), 0);
/* If error or eof, terminate the connection */
if (nread < 1)
{
for (k = 0; k < 6; k++)
{
if (room[k].person1 == i)
{
room[k].person1 = 99;
}
else if (room[k].person2 == i)
{
room[k].person2 = 99;
}
}
close(client[i]);
client[i] = 0;
ActiveClients--;
printf("Disconnected : %s\n", inet_ntoa(their_addr.sin_addr));
logConnections(2, inet_ntoa(their_addr.sin_addr));
}
else
{
if (msgcount[i] == 0)
{
int r = atoi(buf);
char conmsg[] = "You are connected to room ";
strcat(conmsg, buf);
//check room range
if (r > 0 && r <= 5)
{
if (room[r].person1 == 99)
{
//assing client to first person
room[r].person1 = i;
send(client[i], conmsg, strlen(conmsg) + 1, 0);
msgcount[i]++;
}
else if (room[r].person2 == 99)
{
//assing client to second person
room[r].person2 = i;
send(client[i], conmsg, strlen(conmsg) + 1, 0);
msgcount[i]++;
}
else
{
//room is full
send(client[i], rejectmessage, strlen(rejectmessage) + 1, 0);
}
}
else
{
//if we dont have room you will get error
send(client[i], roomerror, strlen(roomerror) + 1, 0);
}
}
else
{
for (k = 0; k < 6; k++)
{
if (room[k].person1 == i)
{
//if person2 is null then will send alone message
if (room[k].person2 == 99)
{
send(client[i], alonemsg, strlen(alonemsg) + 1, 0);
break;
}
else
{
send(client[room[k].person2], buf, nread, 0);
logMessages(i, room[k].person2, buf, room[k].roomid);
buf[0] = '\0';
break;
}
//if person1 is null then will send alone message
}
else if (room[k].person2 == i)
{
if (room[k].person1 == 99)
{
send(client[i], alonemsg, strlen(alonemsg) + 1, 0);
break;
}
else
{
send(client[room[k].person1], buf, nread, 0);
logMessages(i, room[k].person1, buf, room[k].roomid);
buf[0] = '\0';
break;
}
}
}
}
}
}
/* if there is a request for a new connection */
if (FD_ISSET(sockfd, &fds))
{
/* If no of active clients is less than MAX clientaccept the request */
if (ActiveClients < MAX)
{
found = 0;
for (i = 0; i < MAX && !found; i++)
if (client[i] == 0)
{
client[i] = accept(sockfd, (struct sockaddr *)&their_addr, &clientaddr);
found = 1;
ActiveClients++;
printf("Connected : %s\n", inet_ntoa(their_addr.sin_addr));
logConnections(1, inet_ntoa(their_addr.sin_addr));
}
}
}
}
}
Hi i need to convert my java code to C but its been really difficult.
This is my code that i need to convert:
import java.lang.Math.sqrt;
import java.math.RoundingMode;
import java.lang.Math;
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.Scanner;
// Calculating the digits of PI using the Chudnovsky algorithm
public class PIDigits {
// Utility function to calculate factorials
public static double factorial(int n)
{
if(n==0)
{
return 1;
}
else
{
return n*factorial(n-1);
}
}
/**
* Returns a term of from the infinite series in the Chudnovsky algorithm.
* @param n represents the term (nth term)
* @return a double representing the nth term, approximately equal to 1/Pi
*/
public static double chudnovsky(int n)
{
// From the numerator
double numerator = Math.pow(-1,n)*factorial(6*n) * (545140134*n + 13591409);
// From the denominator
double denominator = factorial(3*n) * Math.pow(factorial(n), 3) * Math.pow(640320,3.0*n+3.0/2.0);
if (n==0)
{
return 12.0*numerator/denominator;
}
return 12.0*numerator/denominator + chudnovsky(n-1);
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of digits you want to see from PI.\nUp to 14 digits");
int n = 0;
while(sc.hasNext())
{
// If invalid input, exit the loop/program
try
{
n = sc.nextInt();
}
catch(InputMismatchException e)
{
System.out.println("Invalid value (letters, float, etc). EXITING");
break;
}
finally{
if(n>14)
{
n=14;
}
else if(n<0)
{
System.out.println("Invalid value (negative value)");
n = sc.nextInt();
}
// Formatting the output to have specified digits
NumberFormat fmt = NumberFormat.getInstance(Locale.US);
fmt.setMaximumFractionDigits(n);
fmt.setRoundingMode(RoundingMode.FLOOR);
System.out.println(fmt.format(1.0/chudnovsky(2)));
}
}
sc.close();
}
}}
This is what ive done:
#include<math.h>
#include<stdio.h>
double factorial(int n)
{
if(n==0)
{
return 1;
}
else
{
return n*factorial(n-1);
}
}
/**
* Returns a term of from the infinite series in the Chudnovsky algorithm.
* @param n represents the term (nth term)
* @return a double representing the nth term, approximately equal to 1/Pi
*/
double chudnovsky(int n)
{
// From the numerator
double numerator = pow(-1,n)*factorial(6*n) * (545140134*n + 13591409);
// From the denominator
double denominator = factorial(3*n) * pow(factorial(n), 3) * pow(640320,3.0*n+3.0/2.0);
if (n==0)
{
return 12.0*numerator/denominator;
}
return 12.0*numerator/denominator + chudnovsky(n-1);
}
int main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of digits you want to see from PI.\nUp to 14 digits");
int n = 0;
while(sc.hasNext())
{
// If invalid input, exit the loop/program
try
{
n = sc.nextInt();
}
catch(InputMismatchException e)
{
System.out.println("Invalid value (letters, float, etc). EXITING");
break;
}
finally{
if(n>14)
{
n=14;
}
else if(n<0)
{
printf("Invalid value (negative value)");
n = scanf("%d");
}
// Formatting the output to have specified digits
NumberFormat fmt = NumberFormat.getInstance(Locale.US);
fmt.setMaximumFractionDigits(n);
fmt.setRoundingMode(RoundingMode.FLOOR);
System.out.println(fmt.format(1.0/chudnovsky(2)));
}
}
sc.close();
}
}}
Any help will be appreciate thanks.
Hi i need to convert my java code to C but its been really difficult.
This is my code that i need to convert:
import java.lang.Math.sqrt;
import java.math.RoundingMode;
import java.lang.Math;
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.Scanner;
// Calculating the digits of PI using the Chudnovsky algorithm
public class PIDigits {
// Utility function to calculate factorials
public static double factorial(int n)
{
if(n==0)
{
return 1;
}
else
{
return n*factorial(n-1);
}
}
/**
* Returns a term of from the infinite series in the Chudnovsky algorithm.
* @param n represents the term (nth term)
* @return a double representing the nth term, approximately equal to 1/Pi
*/
public static double chudnovsky(int n)
{
// From the numerator
double numerator = Math.pow(-1,n)*factorial(6*n) * (545140134*n + 13591409);
// From the denominator
double denominator = factorial(3*n) * Math.pow(factorial(n), 3) * Math.pow(640320,3.0*n+3.0/2.0);
if (n==0)
{
return 12.0*numerator/denominator;
}
return 12.0*numerator/denominator + chudnovsky(n-1);
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of digits you want to see from PI.\nUp to 14 digits");
int n = 0;
while(sc.hasNext())
{
// If invalid input, exit the loop/program
try
{
n = sc.nextInt();
}
catch(InputMismatchException e)
{
System.out.println("Invalid value (letters, float, etc). EXITING");
break;
}
finally{
if(n>14)
{
n=14;
}
else if(n<0)
{
System.out.println("Invalid value (negative value)");
n = sc.nextInt();
}
// Formatting the output to have specified digits
NumberFormat fmt = NumberFormat.getInstance(Locale.US);
fmt.setMaximumFractionDigits(n);
fmt.setRoundingMode(RoundingMode.FLOOR);
System.out.println(fmt.format(1.0/chudnovsky(2)));
}
}
sc.close();
}
}}
This is what ive done:
#include<math.h>
#include<stdio.h>
double factorial(int n)
{
if(n==0)
{
return 1;
}
else
{
return n*factorial(n-1);
}
}
/**
* Returns a term of from the infinite series in the Chudnovsky algorithm.
* @param n represents the term (nth term)
* @return a double representing the nth term, approximately equal to 1/Pi
*/
double chudnovsky(int n)
{
// From the numerator
double numerator = pow(-1,n)*factorial(6*n) * (545140134*n + 13591409);
// From the denominator
double denominator = factorial(3*n) * pow(factorial(n), 3) * pow(640320,3.0*n+3.0/2.0);
if (n==0)
{
return 12.0*numerator/denominator;
}
return 12.0*numerator/denominator + chudnovsky(n-1);
}
int main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of digits you want to see from PI.\nUp to 14 digits");
int n = 0;
while(sc.hasNext())
{
// If invalid input, exit the loop/program
try
{
n = sc.nextInt();
}
catch(InputMismatchException e)
{
System.out.println("Invalid value (letters, float, etc). EXITING");
break;
}
finally{
if(n>14)
{
n=14;
}
else if(n<0)
{
printf("Invalid value (negative value)");
n = scanf("%d");
}
// Formatting the output to have specified digits
NumberFormat fmt = NumberFormat.getInstance(Locale.US);
fmt.setMaximumFractionDigits(n);
fmt.setRoundingMode(RoundingMode.FLOOR);
System.out.println(fmt.format(1.0/chudnovsky(2)));
}
}
sc.close();
}
}}
Any help will be appreciate thanks.
Let's look back at some memorable moments and interesting insights from last year.
Your top 10 posts:
Hey everyone, I am a complete beginner currently stuck in a homework. The problem/answer is probably something really dumb and simple but I just can't do programming, no matter how hard I try, it just doesn't "click." I can't get myself in the mindset of thinking how the program will read my inputs. The fact I am trying to do this while at work makes it that much harder.
Anyways, the homework is to do a poker game using specifically linked lists. I can't even get the list initialized. I think, when I try and print them it just prints "14C" over and over.
My reasoning (again, probably the whole issue) is that I create a loop with j and i, and when i is 0 (or "H" for hearts), then the faces will be assigned values form 0-12, then i will increase by 1, and become S, and the process will repeat itself for all 4 suits. But it's not working.
(I have FACES and SUITS defined a 13 and 4, btw.)
int main() {
Card deck[SIZE];
Card* head = NULL, * tail = NULL, * temp;
int i, j, face; /*counter*/
int x = 1;
int y = 1;
char suit;
//All the above you can disregard, I've been trying so many different things and //nothing works.
for (i = 0; i < SUITS; i++) {
if (i = 0) { temp->suit = 'H'; }
else if (i = 1) { temp->suit = 'S'; }
else if (i = 2) {temp->suit = 'D';}
else if (i = 3) { temp->suit = 'C'; }
for (j = 0; j < FACES; j++) {
temp = (Card*)malloc(sizeof(Card));
temp->suit = i;
temp->face = j;
if (head == NULL) {
head = temp;
}
else {
//make next pointer member of tail point to temp
tail->next = temp;
}
tail = temp; // updating tail
tail->next = NULL; // setting next pt. of tail to null.
//allocate the memory for the next (new) node
head = (Card*)malloc(sizeof(Card));
}
}
Am I even on the right track?
Thanks in advance! I'll probably have some more questions soon after but I am hopeful that once I can figure out what I am doing wrong with initializing the list I might be able to use that for the rest.
Edit: I don’t know what I broke but now it’s even telling me “Temp” is uninitialized, although it was just working a few minutes ago.
Edit2: So I played around more, and I realized that for the "if" I am using a single =, not two, so I'm pretty sure that was messing it up. Now it is working. But I got another question: I printed the cards within the loop, and this works. But when I try to print out of the loop, it prints the same card 52 times. My printf code is:
//printf("Deck before: \n");
//for (i = 0; i < SUITS; i++) {
// for (j = 0; j < FACES; j++) {
// printf("%d%c ", temp->face, temp->suit);
// }
// printf("\n");
//}
What am I doing wrong with that?
The user input cannot put in int that is 0. Or anything above 25. If they do, I need an error message and to repeat the question again.
I would need to put in something like this. But I don't know how, or where to put it. I keep getting an error.
if (number1 < 0);
printf("Must choose a number greater than 0 or below 25");
else
(number1 > 25);
printf("Must choose a number greater than 0 or below 25");
int main(void)
{
int number1, number2; int sum;
printf("Enter the first integer to add: "); scanf("%d",&number1);
printf("Enter the second integer to add: "); scanf("%d",&number2);
sum = number1 + number2;
printf("Sum of %d and %d = %d \n",number1, number2, sum);
return 0; }
here is what i need to do...
Write a C# application that implements a class ‘Employee’ with the following members. i. Six private data members ‘BasicSalary’, ‘HRA’, ’Deductions’, ‘Allowance’, ‘Insurance’ and ‘NetSalary’ of integer data type.
ii. A default constructor to display the message “Employee Pay Bill”.
iii. Four public methods, setMembers(), calcDed(), calcNet(), and disResult().
setMembers() – set the values of BasicSalary as 2000, HRA as 200, Insurance as 100 and Allowance as 50.
calcDed() – calculate and return the Deductions using the formulae “Deductions = Insurance + Allowance”.
calcNet() – calculate and return the NetSalary using the formulae “NetSalary = BasicSalary + HRA – Deductions”.
disResult() – display BasicSalary, HRA, Deductions and NetSalary
the output should look like
Employee Pay Bill
Basic Salary = 2000
HRA = 200
Deductions = 150
Net Salary = 2050
it says i have 6 errors
and this is the class Employee
using System;
using System.Collections.Generic;
using System.Text;
namespace Final_THE_M109
{
class Employee
{
private int BasicSalary;
private int HRA;
private int Deductions;
private int Allowance;
private int Insurance;
private int NetSalary;
public void setMembers(int B, int H, int A, int I)
{
BasicSalary = B;
HRA = H;
Allowance = A;
Insurance = I;
}
public int calDed()
{
int Deductions = Insurance + Allowance;
return Deductions;
}
public int calcNet()
{
int NetSalary = BasicSalary + HRA – Deductions; // i get a red line under the (-) and (deductions)
return NetSalary
}
public void disResult()
{
Console.WriteLine("Basic Salary = ", setMembers(B)); // i also get a red line under (B)
Console.WriteLine("HRA = ", setMembers(H));// a line under (H) too
Console.WriteLine("Deductions = ", calDed());
Console.WriteLine("Net Salary = ", calcNet());
}
}
}
now the code for the main method
using System;
namespace QuestionTwo
{
class Program
{
public static void Main(string[] args)
{
Employee e = new Employee();
Console.WriteLine("Employee Pay Bill");
// it gives me a red line under every setMembers
int B = 2000;
e.setMembers(B);
int H = 200;
e.setMembers(H);
int A = 50;
e.setMembers(A);
int I = 100;
e.setMembers(I);
e.disResult();
}
}
}
using System;
public class Program
{
public static void Main(string[] args)
{
int i, j;
int [,] A = new int[5,5];
for (i = 0; i < 5; ++i)
{
for (j = 0; j < 5; ++j)
{
A[i,j] = i*i;
}
}
for (i = 0; i < 4; ++i)
{
for (j = 0; j < 5; ++j)
{
if (i < 5)
{
A[j, i] = A[i, j];
}
else
break;
Console.Write(A[i, j] + " ");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
and the output is
0 0 0 0 0
0 1 1 1 1
0 1 4 4 4
0 1 4 9 9
I'm doing exercise 5-3 in The c programming language. My strcat version is:
void stringcat(char *s, char *t)
{
while (*s++);
while (*s++ = *t++);
}
supposed to add t to the end of s. But it doesn't work:
int main()
{
char s[100] = "baboon";
char t[] = "whale";
stringcat(s, t);
printf("%s\n", s);
return 0;
}
Main just prints out 'baboon'. I don't understand, first I loop so s points to '\0' and then I set it to w and h and so on. But string s is still only 'baboon'.
I'm making a hotel management system, now i wrote most of the code but i can't understand how to write a code which when I enter a room features it have to be saved in it and to the program itself so when another guest comes and try to enter the same room it tells them that it is occupied then search for another same room feauters for him if not it gives them another room with another features but if all the rooms are occupied the programm tells the user that he can't reserve one.
*Sorry its long but to not trouble ya all with understanding what i means
here is my code :
#include <stdio.h>
#include <stdlib.h>
#define AMOUNT 8
void initialize_hotel(char**** hotel, int n, int m)
{
int i,j;
*hotel=(char***)malloc(n*sizeof(char*));
if(!*hotel)
{
printf("Memory Allocation Error!!\n");
exit(1);
}
for (i=0; i<n; i++)
{
(*hotel)[i]=(char**)malloc(m*sizeof(char*));
if (!(*hotel)[i])
{
printf("Memory Allocation Error!!\n");
exit(1);
}
for (j=0; j<m; j++)
{
(*hotel)[i][j]=(char*)malloc(AMOUNT*sizeof(char));
if(!(*hotel)[i][j])
{
printf("Memory Allocation Error!!\n");
exit(1);
}
}
}
}
void rooms_features(char*** hotel, int n, int m)
/*in this function its the openning of the hotel and i enter the rooms i want their features*/
{
int i,j;
void initialize_hotel(char**** hotel, int n, int m);
for(i = 0; i < n; i++)
{
for(j = 0; j < m; j++)
{
if ((i==0 && j==0)|| (j%2==0 && i!=0 && i!=n-1) || (i==0 && j==m-1) || (i==n-1 && j==m-1)|| (i==n-1 && j==0))
{
printf("insert features: ");
scanf("%s",**hotel);
}
}
}
}
void menu_one(char *order_type);
void options();
int main()
{
int row,cols;
char id[AMOUNT]
printf("Please enter the size of the hotel represented by rows and columns:\n");
printf("rows: ");
scanf("%d",&row);
while(row<=2)
{
printf("rows number should be bigger than 2.\n");
scanf("%d",&row);
}
printf("cols: ");
scanf("%d",&cols);
while(cols%2==0||cols<0)
{
printf("columns number should be odd positive number.\n");
scanf("%d",&cols);
}
rooms_features(&id,row,cols);
options();
return 0;
}
void options()
{
int menu_option;
char s;
do
{/*in this function it open the menu for the guest to choose from it */
printf("1. Rent room rooms.\n");
printf("2. check out.\n");
printf("3. close hotel.\n");
scanf("%d",&menu_option);
if (!menu_option || (menu_option<1 || menu_option>3))
{
printf("choose option:choose option between 1-3:\n");
}
switch (menu_option)
{
case 1:
menu_one(&s);
continue;
case 2:
/*in progress*/
break;
case 3:
/*in progress*/
break;
}
}
while(menu_option>=1 && menu_option<=3);
}
void menu_one(char *order_type)
{/*in this function when the user enters from the menu number 1 it enters this function, now i did all the steps here but I can't make it that when a room has been reserved from a geust before to save it as occupied and then make the program
search for another room with the same features if not then give it another room */
int user_id, booked_days;
int num_of_people,rooms_ordered;
char preferred_view;
int i,E=0,O=1;
printf("choose option:Do you want to order individually or in groups? ");
scanf("%s",order_type);
while(*order_type!='I' && *order_type!='G')
{
printf("Choose between I as personal and G as group? ");
scanf("%s",order_type);
}
switch(*order_type)
{
case 'I':
printf("Some details should be provided to choose you a satisfying room: \n");
printf("How many days will you stay in the hotel:");
scanf("%d",&booked_days);
printf("Id ");
scanf("%d",&user_id);
printf("number of people in room: ");
scanf("%d",&num_of_people);
printf("preferred view (options: B - beach, P - pool, G - garden, N - None):");
scanf("%c",&preferred_view);
printf("1 room has rented!\n");
printf("Welcome to our Hotel, may you enjoy your time!\n");
break;
case 'G':
i=1;
printf("How many rooms do you need in total? ");
scanf("%d",&rooms_ordered);
printf("Some details should be provided to choose you a satisfying room: \n");
printf("How many days will you stay in the hotel:");
scanf("%d",&booked_days);
printf("Id ");
scanf("%d",&user_id);
printf("number of people in room: ");
scanf("%d",&num_of_people);
printf("preferred view (options: B - beach, P - pool, G - garden, N - None):");
scanf("%s",&preferred_view);
printf("%d room has rented!",i);
if (rooms_ordered>1)
{
do
{i++;
printf("number of people in room: ");
scanf("%d",&num_of_people);
printf("preferred view (options: B - beach, P - pool, G - garden, N - None):");
scanf("%s",&preferred_view);
printf("%d room has rented!",i);
}
while(i<=rooms_ordered);
break;
}
}
I have to make a program where it reads from a file and then enter a string with letter, symbols and numbers and then it have to print only the letters in reverse way, now i have to use recursive function for the letters and I must use prints in the main function not in the recursive function for example if the file the program reads from has :
input :#$f^t&^$q&%Y &^q~!$n!@n&@g%$#J*/&^(%
output : Hello Word
NOTE : ALL that wouldn't happen to me if I haven't been asked to use print only in the main function, and also when there is a symbol or number it avoids the if statements and the function
The main question is : how I can use printf in the main function and be used properly where it should print reverse way and the symbols shouldn't be shown, in the function itself those thing works btw
here is my code :
int decode(char x[])
{
if (!x[0])
{
return 1;
}
decode(x+1);
if ( x[0]== ' ' || x[0]== ',' ||((x[0]>='A' && x[0]<='Z') || (x[0]>='a' && x[0]<='z' ) ) )
{ // here each string i enter at makes it backward by -2 for example c-->a
switch(x[0])
{
case 'A':
x[0]='Y';
break;
case 'B':
x[0]='Z';
break;
case 'a':
x[0]='y';
break;
case 'b':
x[0]='z';
break;
case ',':
x[0]=',';
break;
case ' ':
x[0]=' ';
break;
default:
x[0]-=2;
break;
}
else
return ;
}
here is the main function
int main()
{
FILE *fp;
char str[1000];
char filename[100];
scanf("%s",filename);// here i have to enter the file name to get all the strings from another file //
fp = fopen(filename, "r");
if (fp == NULL)
{
printf("Could not open file %s",filename);
return 1;
}
while (fgets(str,1000, fp) != NULL)// the problem start here it get the strings input
{
decode(str);
printf("%s",str);// and in the printf it prints everything where it should only print the letters in revrse way
fclose(fp);
}
hi guys,
i'm kinda new to the c
i have this homework where one of the tasks is like this :
i have a maximum of 20 steps :
the guys have to start from n[0] to n[19]
how it works fisrt step he should move 2 steps forward and then one backward
then 3 steps forward and one backward ( and everytime add one step to the forward steps and keeps the backward steps 1)
and then it should sum the backward steps including step n[0];
and if there was a steps left to do and it can't continue because the max is 20 it shouldn't add it to the sum.
well here is my code:
please help me understand what i explained to what i have to do in my code to make it work :
it only sums the odd arrays here in my code
#define T 20
int steps(int a[])
{
int i,j=1,sum=0;
for(i=0; i<T;i++)
{
i++;
sum+=a[i];
// what I'm trying to do here is make the program start by two steps forward then
backwards and then save the array that it have stopped on, after that it
countinues from where it stopped and then moving 3 steps forward and then 1
backward and (save the array that it stopped at) and continuing like this until
it reaches the T Then sums all the arrays that it has stopped on
}
return sum;
}
int main ()
{
int,i,n[T],sum=0;
{
scanf("%d",&n[i]);
}
sum=steps(n);
printf("sum of array is :%d",sum);
return 0;
}
I am taking software for electricians and as the title states I need to find the sum and average in multiples of 3, here is what I have so far: I can't seem to find where the problem lies to get the correct sum and average of the output multiples of 3
printf("Enter the start and stop range voltage values with comma: ");
scanf("%d, %d", &strt, &stop);
printf("\nFind multiple of three voltages in range from %dv to %dv are: \n", strt, stop);
for(cntr=strt; cntr<=stop; cntr++)
{
if (cntr % 3== 0)
printf("%dv; ", cntr);
sum = sum + cntr;
}
avg = sum / cntr;
printf("\nFrom %dv to %dv the multiple of three voltages sum= %d\n", strt, stop, sum);
printf("From %dv to %dv the multiple of three voltages average= %.2f\n", strt, stop, avg);
return 0;
Hey everyone! I've read the first two chapters of Effective C. and I love it. I think it's a really good book. Here's the question:
Listing 2-6
void increment(void) {
static unsigned int counter = 0;
counter++;
printf("%d ", counter);
}
int main(void) {
for (int i = 0; i < 5; i++) {
increment();
}
return 0;
}
I've "solved" the first exercise in a few different ways. For my first solution, I moved counter to a global variable. For the second, I just realized I messed up and it doesn't work. I'm wondering if moving counter to the global scope is what the author would accept as a good solution to the problem, I feel like he wouldn't. What I would like to do is write a retrieve function without passing any variables into it, and without moving counter to the global scope, but I feel like that won't work because of scope rules.
I am doing an affine cypher program that cracks the cypher using brute force and returns only the plaintext(or what it is likely to be).
I have the brute force complete but it prints every possible output 11*26. How would I store every combination as separate elements of a char array to perform a dictionary check to find the one that has actual words in it?
Thank you in advance.
N University is in need of an information system to register students that voluntarily want to participate in the Covid Vaccination program. Due to the vaccination room, physical limitations, and social distancing guidelines the center can't vaccinate more than 10 students at a time.
1.- You program will collect the name of 10 students storing them in a linked list queue.
2.- Your program will display the name of the students ordered (FIFO) on the screen
3.- Your program will ask if the end-user wants to clean the queue (Y/N question).
3.1 - If the answer is yes, your program will dequeue all the nodes of the list and start asking for the names of the next batch of 10
students to process.
3.2 - If the answer is no then your program will exit.
- You will use and adjust the class header below.
- You will include comments in your code
- You will a linked list to implement a queue, you will use struct(s), and you will use at least a repetition flow control structure.